I have the following code:
SimpleDateFormat format=new SimpleDateFormat("yyyy.MM.dd HH:mm");
try {
Date date=format.parse("2012.9.11 02:00");
Log.i("date", date.toGMTString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("exception", e.getMessage());
}
But I've got the message: "10 Sep 2012 22:00:00 GMT", i.e. incorrect date. How can I fix it?
That IS the correct date. It is calculated based on your GMT offset.
To print it like this 11-Sep-2012 02:00:00 use date.toLocaleString() (deprecated method)
Or you can print the date using the Calendar class using:
SimpleDateFormat format=new SimpleDateFormat("yyyy.MM.dd HH:mm");
Date date=format.parse("2012.09.11 02:00");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(format.format(cal.getTime()));
This prints : 2012.09.11 02:00
You can see http://www.vogella.com/articles/JavaDateTimeAPI/article.html for more info
You're printing date.toGMTString() and so you get "10 Sep 2012 22:00:00 GMT" which isn't an incorrect string but the date in Greenwich Mean Time. Note that toGMTString is deprecated.
If you want to print your date in your format, you may do
Log.i("date", format.format(date));
If you don't want to get supplementary "0", use
format=new SimpleDateFormat("yyyy.M.d HH:mm");
The method toGMTString() is deprecated.
However, as for an explanation, you might be in different time zone, thus have a different locale.
Try replacing with date.toLocaleString() should output correctly, although also a deprecated method.
As Per JavaDoc, date.toGMTString() is a deprecated method.
Its not good practice to use deprecated methods.
Use date.toString() instead of date.toGMTString().
Or
format.format(date);
It is incorrect because you're using date.toGMTString()
Just try to output the variable date and you'll able to see the correct time!
Related
I am getting an exception when parsing date 20160327020727 with format yyyyMMddhhmmss. Note that the lenient is set to false.
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
df.setLenient(false);
try {
Date dt = df.parse("20160327020727");
} catch (ParseException e) {
e.printStackTrace();
}
It is parsing other dates with the same format and it is working as expected. Why is this happening?
CET changes to summer time the last Sunday of march, so there is no 2AM this day.
You go from 1:59 to 3:00
You are getting an error because that time does not exist in your default time zone.
Try setting the timezone to UTC by doing df.setTimeZone(TimeZone.getTimeZone("UTC"));
In CET on the last Sunday of march it changes to summertime -> No 2AM on that day.
Change it to "yyyyMMdd HHmmss", so you can parse it easily.
I'm receiving a date as a String like this :2015-07-22.06.05.56.344. I wrote a parsing code like this
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd.hh.MM.ss.ms");
try {
Date date = sdf.parse("2015-07-22.06.05.56.344");
System.out.println(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And I got the output like this:
Fri May 22 06:03:44 IST 2015
Why is it reading it wrongly? Is it an issue with my code or java cannot recognize this date format?
Your MM/mm are around the wrong way, mm is for "Minute in hour" and MM is for "Month in year"
SS is for "Millisecond" (or ms, which means nothing)
I'd also recommend using HH instead of hh as HH is for "Hour in day (0-23)"
So, using...
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd.HH.mm.ss.SS");
It outputs Wed Jul 22 06:05:56 EST 2015 for me
You need to use MM for months and mm for minutes.
Try setting SimpleDateFormat to this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd.hh.mm.ss.SSS");
Check javadoc for more info:
SimpleDateFormat
You have the wrong pattern. The pattern is case sensitive.
mm stands for minutes
MM stand for month.
SS is miliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd.hh.mm.ss.SSS");
For more details see the SimpleDateFormat documentation
I'm having huge difficulties with simple date format. First of all, I know not all tutorials on all sites are actually good, but the fact that all non trivial formats (not dd/MM/yyyy) gave a parse exception (plus my own tests don't work as expected) is rather frustrating to me.
This is the site in question: http://www.mkyong.com/java/how-to-convert-string-to-date-java/
And I don't understand why something as simple as:
private static void unexpectedFailure() {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
Throws a parse exception.
Also besides that, I'm trying to parse my own dates. This code gives strange results (unexpected I would say):
public static void doSomething(List<String> list) {
Iterator<String> iter = list.iterator();
String[] line = iter.next().split(" ");
System.out.println(Arrays.toString(line));
DateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
format.setLenient(true);
try {
System.out.println(line[0]+" "+line[1]);
System.out.println(format.parse(line[0]+" "+line[1]));
} catch (ParseException e) {
System.out.println("In theory this should not get caught.");
}
}
Prints out this:
[06/08/2015, 13:51:29:849, DEBUG, etc...]
06/08/2015 13:51:29:849
Thu Aug 06 13:51:29 EEST 2015
Thu Aug 06 13:51:29 EEST 2015 WHAT? WHY?
EDIT I'll try and explain. In my last code snippet I'm just trying to determine if the string is a date, and it passes "the test". However when I'm printing it out the format is simply bizzare. I'm starting to think that is because I'm printing a date. How can I even print a DateFormat? What I was expecting was dd/MM/yyyy hh:mm:ss not ddd MMM 06? hh:mm:ss G YYYY
And I don't understand why something as simple as:
(code snipped)
Throws a parse exception.
My guess is that it's tripping up over Jun which may not be a valid month abbreviation in your system default locale. I suggest you specify the locale in your SimpleDateFormat constructor:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
Then you're dealing with a locale which definitely has Jun as a month abbreviation.
That said, where possible I'd suggest using numeric formats where possibly, ideally ones following ISO-8601, e.g.
yyyy-MM-dd'T'HH:mm:ss
However when I'm printing it out the format is simply bizzare.
No it's not. You're effectively using
Date date = format.parse(line[0]+" "+line[1]);
System.out.println(date);
So that's calling Date.toString(), documented as:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
So that's working as expected. However, you want to format the date using your SimpleDateFormat - so you need to call format:
System.out.println(format.format(date));
Of course that just checks that it can round-trip, basically.
As a side note, I suspect you want HH (24-hour clock) instead of hh (12-hour clock) in your format string.
I used same methods to generate date and time in java application and an android application , but i got surprised to see that the output produced by the same function is different, i am amused why this happen when we use the methods in two different platforms, can anybody please explain.
Here is the output
Java application output ---Fri Jul 18 12:51:17 IST 2014
Android application output----Thu Jul 17 18:46:05 GMT+05:30 2014
Here is the code which returns date [same code used for same applications]
private Date offsetTimeZone(Date date, String fromTZ, String toTZ) {
// Construct FROM and TO TimeZone instances
TimeZone fromTimeZone = TimeZone.getTimeZone(fromTZ);
TimeZone toTimeZone = TimeZone.getTimeZone(toTZ);
System.out.println("timezone:" + fromTimeZone);
// Get a Calendar instance using the default time zone and locale.
Calendar calendar = Calendar.getInstance();
// Set the calendar's time with the given date
calendar.setTimeZone(fromTimeZone);
calendar.setTime(date);
System.out.println("Input: " + calendar.getTime() + " in "
+ fromTimeZone.getDisplayName());
// UTC to TO TimeZone
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
return calendar.getTime();
}
Calling the method from android application
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.ENGLISH).parse(_data.get(position).get_date());
date2 = offsetTimeZone(date, "UTC", timezoneID);
Calling the method from java application
try {
String timezoneID = TimeZone.getDefault().getID();
System.out.println("idd:" + timezoneID);
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.ENGLISH).parse("2014-07-18 07:21:17");
Date date2 = offsetTimeZone(date, "UTC", timezoneID);
System.out.println("output" + date2.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It's not a complete answer but to help narrow it down...
This documents exactly what format you should expect:
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString%28%29
http://developer.android.com/reference/java/util/Date.html#toString%28%29
Both Android and regular Java use the same format for their output.
For some reason zzz in one example is being displayed as GMT+05:30 and in the other it is being displayed as IST.
It is possible that the timezone naming database does not know the name of IST in one case and has displayed the timezone offset instead. The Javadoc for regular Java though says "If time zone information is not available, then zzz is empty - that is, it consists of no characters at all." which suggests otherwise.
My input is String formated as the following:
3/4/2010 10:40:01 AM
3/4/2010 10:38:31 AM
My code is:
DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss aa");
try
{
Date today = dateFormat.parse(time);
System.out.println("Date Time : " + today);
}
catch (ParseException e)
{
e.printStackTrace();
}
the output is:
Sun Jan 03 10:38:31 AST 2010
Sun Jan 03 10:40:01 AST 2010
I'm not sure from where the day (Sun) came from? or (AST)? and why the date is wrong? I just wanted to keep the same format of the original String date and make it into a Date object.
I'm using Netbeans 6.8 Mac version.
Should be MM, not mm. The lowercase mm is for minutes, not months.
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
MM, not mm for months. You are using mm twice - and logically, it's the same things - minutes.
If you want to print the date in the original format, use the format method:
System.out.println("Date Time : "+ dateFormat.format(today));
the "weird" format comes from Date's toString implementation, the javadoc says:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
"I just wanted to keep the same format of the original String date and make it into a Date object."
The Date Object is intended to represent a specific instant in time, you can't keep the format of the original string into it, that's why we have the DateFormat Class.
The answer is simple. You have displayed the Date.toString() value of today and not the intended dateFormat version. what you require is:
System.out.println("Date Time : " + dateFormat.format(today) );
Printing the Date out using System.out.println() results in the toString() method being called on the Date object.
The format string used in toString() is what is causing the Day of the week and the timezone to appear in the output.
This is apart from the parsing mistake pointed out by Duffy.