How do I create the java date object without time stamp [duplicate] - java

This question already has answers here:
Java program to get the current date without timestamp
(17 answers)
Closed 6 years ago.
I want to create a Date object without a TimeZone (eg : 2007-06-21). Is this possible?
When I use the following method it prints like Thu Jun 21 00:00:00 GMT 2007
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setDefault(timeZone);
sdf.setTimeZone(timeZone);
Date pickUpDate = sdf.parse("2007-06-21");
System.out.println(pickUpDate);

If you want to format a date, you need to use DateFormat or something similar. A Date is just an instant in time - the number of milliseconds since the Unix epoch. It doesn't have any idea of time zone, calendar system or format. The toString() method always uses the system local time zone, and always formats it in a default way. From the documentation:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
So it's behaving exactly as documented.
You've already got a DateFormat with the right format, so you just need to call format on it:
System.out.println("pickUpDate" + sdf.format(pickUpDate));
Of course it doesn't make much sense in your sample, given that you've only just parsed it - but presumably you'd normally be passing the date around first.
Note that if this is for interaction with a database, it would be better not to pass it as a string at all. Keep the value in a "native" representation for as much of the time as possible, and use something like PreparedStatement.setDate to pass it to the database.
As an aside, if you can possibly change to use Joda Time or the new date/time API in Java 8 (java.time.*) you'll have a much smoother time of it with anything date/time-related. The Date/Calendar API is truly dreadful.

This is the toString() of the java.util.Date
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
So, if you will pass a Date and try to print it this will be printed out all the time.

Code:
Date date = new Date();
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
Date : Fri Apr 29 04:53:16 GMT 2016
Sample Output : 2016-04-29
Imports required :
import java.util.Date; //for new Date()
import java.text.SimpleDateFormat; // for the format change

System.out.println("pickUpDate " + sdf.format(pickUpDate));
You can use the above code to get formatted Date as String

Use this Code:
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date pickUpDate =sdf.parse("2007-06-21");
System.out.println("pickUpDate "+sdf.format(pickUpDate));
Hope it'll help you.

String your_format_date=sdf.format(pickUpDate);
System.out.println("pick Up Date " + your_format_date);

Date isn't a date. It's a timestamp. That's some impressive API design, isn't it?
The type you need is now java.time.LocalDate, added in Java 8.
If you can't use Java 8, you can use ThreeTen, a backport for Java 7.

Related

Generic date parsing in java

I have date strings in various formats like Oct 10 11:05:03 or 12/12/2016 4:30 etc
If I do
// some code...
getDate("Oct 10 11:05:03", "MMM d HH:mm:ss");
// some code ...
The date gets parsed, but I am getting the year as 1970 (since the year is not specified in the string.) But I want the year as current year if year is not specidied. Same applies for all fields.
here is my getDate function:
public Date getDate(dateStr, pattern) {
SimpleDateFormat parser = new SimpleDateFormat(pattern);
Date date = parser.parse(myDate);
return date;
}
can anybody tell me how to do that inside getDate function (because I want a generic solution)?
Thanks in advance!
If you do not know the format in advance, you should list the actual formats you are expecting and then try to parse them. If one fails, try the next one.
Here is an example of how to fill in the default.
You'll end up with something like this:
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern("ddMM")
.parseDefaulting(YEAR, currentYear)
.toFormatter();
LocalDate date = LocalDate.parse("yourstring", f);
Or even better, the abovementioned formatter class supports optional elements. Wrap the year specifier in square brackets and the element will be optional. You can then supply a default with parseDefaulting.
Here is an example:
String s1 = "Oct 5 11:05:03";
String s2 = "Oct 5 1996 13:51:56"; // Year supplied
String format = "MMM d [uuuu ]HH:mm:ss";
DateTimeFormatter f = new DateTimeFormatterBuilder()
.appendPattern(format)
.parseDefaulting(ChronoField.YEAR, Year.now().getValue())
.toFormatter(Locale.US);
System.out.println(LocalDate.parse(s1, f));
System.out.println(LocalDate.parse(s2, f));
Note: Dates and times are not easy. You should take into consideration that date interpreting is often locale-dependant and this sometimes leads to ambiguity. For example, the date string "05/12/2018" means the 12th of May, 2018 when you are American, but in some European areas it means the 5th of December 2018. You need to be aware of that.
One option would be to concatenate the current year onto the incoming date string, and then parse:
String ts = "Oct 10 11:05:03";
int currYear = Calendar.getInstance().get(Calendar.YEAR);
ts = String.valueOf(currYear) + " " + ts;
Date date = getDate(ts, "yyyy MMM d HH:mm:ss");
System.out.println(date);
Wed Oct 10 11:05:03 CEST 2018
Demo
Note that we could have used StringBuilder above, but the purpose of brevity of code, I used raw string concatenations instead. I also fixed a few typos in your helper method getDate().

SimpleDateFormat Always returning 12.30 AM [duplicate]

This question already has answers here:
Simple date formatting giving wrong time
(4 answers)
Closed 7 years ago.
I am trying to utilise the Calendar apart from implementing my own logic.
I am setting the Calendar value and trying to get the time in a format, below is the code
String timeValue = "06/11/2015 06:30 pm";
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy HH:mm a");
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse(timeValue));
Logger.d(TAG, "Hour is = " + calendar.get(Calendar.HOUR));
SimpleDateFormat slotTime = new SimpleDateFormat("hh:mma");
SimpleDateFormat slotDate = new SimpleDateFormat(", dd/MM/yy");
Logger.d(TAG, " Date = " + slotDate.format(calendar.getTime()) + " Time is = " + slotTime.format(calendar.getTime()));
}catch (ParseException parseEx){
parseEx.printStackTrace();
}
I am expecting slotTime.format(calendar.getTime())) should return 6.30 PM while it is returning 12.30 AM.
How can I get the desired output which is 6.30 PM , What mistake I am doing
Your code is OK. The mistake is on the datetime mask:
The ".SSS" field is too much. This is only to expect for milliseconds, and, as far as I can see, you do not expect milliseconds in your input string.
The "HH" mask should be "hh" for 1-12 hours format.
Thus, let it be:
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm a");
You have to remove milliseconds from your Simple Date Format (SSS).
I get a java.text.ParseException running your code.
Try using a Simple Date Format string of "dd/MM/yyyy HH:mm a"
you have an error with the String in the time format
String timeValue = "06/11/2015 06:30 pm";
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm a.SSS");
a.SSS // .SSS is for Millisenconds which is not correct in the String you are trying to parse.
I removed it and worked fine for me.
Take a look at DateFormat.getTimeInstance(), DateFormat.getDateInstance() and DateFormat.getDateTimeInstance() as these methods return a DateFormat which will honor the users local settings (e.g. 12/24 hour system or date formats like 2016/01/01 or 01.01.2016). This is very important if you plan to release your app in multiple languages. Note that these methods also take a int as parameter with which you can style the resulting format (e.g. short format).
See here for more details.
A complete example would llok like this (creates a String like 3:04 PM on devices with English language and 15:04 on devices with e.g. German language):
String s = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(new Date()); // Creates a String like 3:04 PM

Java 8 Timezone conversion when creating java.util.Date [duplicate]

This question already has answers here:
Java program to get the current date without timestamp
(17 answers)
Closed 6 years ago.
I want to create a Date object without a TimeZone (eg : 2007-06-21). Is this possible?
When I use the following method it prints like Thu Jun 21 00:00:00 GMT 2007
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setDefault(timeZone);
sdf.setTimeZone(timeZone);
Date pickUpDate = sdf.parse("2007-06-21");
System.out.println(pickUpDate);
If you want to format a date, you need to use DateFormat or something similar. A Date is just an instant in time - the number of milliseconds since the Unix epoch. It doesn't have any idea of time zone, calendar system or format. The toString() method always uses the system local time zone, and always formats it in a default way. From the documentation:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
So it's behaving exactly as documented.
You've already got a DateFormat with the right format, so you just need to call format on it:
System.out.println("pickUpDate" + sdf.format(pickUpDate));
Of course it doesn't make much sense in your sample, given that you've only just parsed it - but presumably you'd normally be passing the date around first.
Note that if this is for interaction with a database, it would be better not to pass it as a string at all. Keep the value in a "native" representation for as much of the time as possible, and use something like PreparedStatement.setDate to pass it to the database.
As an aside, if you can possibly change to use Joda Time or the new date/time API in Java 8 (java.time.*) you'll have a much smoother time of it with anything date/time-related. The Date/Calendar API is truly dreadful.
This is the toString() of the java.util.Date
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
So, if you will pass a Date and try to print it this will be printed out all the time.
Code:
Date date = new Date();
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
Date : Fri Apr 29 04:53:16 GMT 2016
Sample Output : 2016-04-29
Imports required :
import java.util.Date; //for new Date()
import java.text.SimpleDateFormat; // for the format change
System.out.println("pickUpDate " + sdf.format(pickUpDate));
You can use the above code to get formatted Date as String
Use this Code:
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date pickUpDate =sdf.parse("2007-06-21");
System.out.println("pickUpDate "+sdf.format(pickUpDate));
Hope it'll help you.
String your_format_date=sdf.format(pickUpDate);
System.out.println("pick Up Date " + your_format_date);
Date isn't a date. It's a timestamp. That's some impressive API design, isn't it?
The type you need is now java.time.LocalDate, added in Java 8.
If you can't use Java 8, you can use ThreeTen, a backport for Java 7.

Date converter in JAVA [duplicate]

This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Closed 9 years ago.
I have date like Tue Mar 19 00:41:00 GMT 2013, how to convert it to 2013-03-19 06:13:00?
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = bdate;
Date ndate = formatter.parse(formatter.format(date));
System.out.println(ndate);
gives the same date.
Use two SimpleDateFormat objects with appropriate formats and use the first to parse the string into a date and the second to format the date into a string again.
As the first answer says. First parse your date with SimpleDateFormat like this:
Date from = new SimpleDateFormat("E M d hh:mm:ss z yyyy").parse("Tue Mar 19 00:41:00 GMT 2013");
Then use that to format the resulting date object with another instance of SimpleDateFormat like this:
String to = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(from);
See the javadoc of SimpleDateFormat here. Hope that helps.
One major thing that the others have left out is dealing with the timezone (TZ). Anytime you use a SimpleDateFormat to go to/from a string representation of the date, you really need to be aware of what TZ you're dealing with. Unless you explicitly set the TZ on the SimpleDateFormat, it will use the default TZ when formatting/parsing. Unless you only deal with date strings in the default timezone, you'll run into problems.
Your input date is representing a date in GMT. Assuming that you also want the output to be formatted as GMT, you need to make sure to set the TZ on the SimpleDateFormat:
public static void main(String[] args) throws Exception
{
String inputDate = "Tue Mar 19 00:41:00 GMT 2013";
// Initialize with format of input
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
// Configure the TZ on the date formatter. Not sure why it doesn't get set
// automatically when parsing the date since the input includes the TZ name,
// but it doesn't. One of many reasons to use Joda instead
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse(inputDate);
// re-initialize the pattern with format of desired output. Alternatively,
// you could use a new SimpleDateFormat instance as long as you set the TZ
// correctly
sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
}
Use SimpleDateFormat in this way:
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = new Date();
System.out.println(formatter.format(date));
If you do any calculations or parsing with dates please use JodaTime because the standard JAVA date support is really buggy

Parsing date from Calendar in Java

I am having following function
public static Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
I am using this as follows in my code
Calendar eDate = Calendar.getInstance();
eDate.add(Calendar.DAY_OF_MONTH,10);
Date date = null;
try {
date = parseDate(eDate.getTime().toString(),"yyyy-MM-dd hh-mm-ss");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it is throwing -
java.text.ParseException: Unparseable date
What is the problem here?
The format is not stored in the Date. It is stored in the String. The Date#toString() returns a fixed format which is described in its Javadoc.
Do the formatting only at the moment you need to display a Date to a human as a String.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 10);
Date date = calendar.getTime();
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(formattedDate);
Note that MM stands for months and mm for minutes. See also SimpleDateFormat javadoc.
You'll be happy to hear that there's never a need to parse a date from a Calendar object: The way to pull a Date out of a Calendar is via the getTime() method.
EDIT:
To output the date in eDate in ISO style format:
final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String formattedDate = isoFormat.format(eDate.getTime());
That's untested, but I think it should work.
You're currently formatting with the default format from java.util.Date, and then parsing with a potentially different format. You should also change your format string - it's currently using a 12 hour clock with no am/pm indicator, and minutes twice. I think you mean: "yyyy-MM-dd HH-mm-ss"
Don't use toString() for anything like that. toString() should be used only for debug messages.
Use DateFormat.format(..) to produce a string in a predictable form.
You're inserting a Zulu Timestamp (UNIX), getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT. Then you define the format as yyyy-mm-dd hh-mm-ss and try to parse the timestamp with this pattern. Which doesn't match.
You could use Date date = calendar.getTime(); and then format it via new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(date);
you can simply use the date returned by the calendar, instead of transforming it into string and back into a date (apparently using a wrong date format). The date can be obtained by:
eDate.getTime()
There seems to be no need for SimpleDateFormat in your case.
Check the Date.toString() method.
The api states that it returns it in
the format:
dow mon dd hh:mm:ss zzz yyyy
which is:
Mon Jan 28 14:22:07 EST 2004
You are telling the parser to expect: 2004-01-28 14-22-07
eDate.getTime().toString()
returns a String representation of a date in this format:
dow mon dd hh:mm:ss zzz yyyy (see the java.util.Date API).
You are trying to parse a date using this format:
yyyy-mm-dd hh-mm-ss .
The code is correctly throwing the ParseException.

Categories

Resources