Good morning! I've been working with the following bit of code for the last two hours, scouring forums, Google and the JDK 1.6 docs for any idea what is going on but can't seem to make this work. I would expect the code to output 07/25/2010 11:59:33 PM but what I get instead is 01/25/2010 11:59:33 PM .
String dateString = "07/25/2010 11:59:33 PM";
DateFormat format = new SimpleDateFormat("MM/DD/yyyy hh:mm:ss a");
Date testDate = format.parse( dateString );
System.out.println(format.format(testDate));
Thinking that it may be something to do with the JDK, I tried writing the same thing using Joda-Time and get the same results. Am I missing something with how DateFormat works?
Thanks in advance for any insight you can provide!
The problem is the "DD" in your format string - it should be "dd".
"DD" means "day of year"... so you're talking about the 25th day of the year, but in the month of July... the "day of year" is taking priority, so you're getting January 25th instead.
DD means day in year as in a Julian day. A Julian day can describe any day in the year, so the month is ignored. Use dd instead (day in month) and you'll get the right result.
U have to take care on case sensitive issues for the formatter. They are a bit weird organised.
Try it with
DateFormat format = new SimpleDateFormat("MM/DD/yyyy hh:mm:ss a");
EDIT: DD means Day in year, dd = day in month
Refering to the JAVA 1.6 API SimpleDateFormat
Related
This question already has answers here:
How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?
(5 answers)
Closed 5 years ago.
I have a problem with date converting. I use the following program and I expect the output: 19.05.2017
But the output is: 05.00.2017
Can anybody help?
String t = "Fri May 19 00:00:00 CEST 2017";
Date d = new SimpleDateFormat("EEE MMM DD hh:mm:ss zzzz YYYY", Locale.US).parse(t);
String s = new SimpleDateFormat("dd.mm.yyyy").format(d).toString();
System.out.println(s);
A surprising result. The oldfashioned classes SimpleDateFormat and friends are full of surprises. This is meant as a negative thing.
Uppercase DD is day of year. Lowercase hh is hour of AM or PM (1 through 12). Uppercase YYYY is weekbased year (only useful with week number). So you are asking for a date that is a Friday in May and the 19th day of the year. Obviously this is not possible.
The result of parsing is Thu Jan 05 23:00:00 CET 2017. Apparently SimpleDateFormat opts for giving you a Friday and for using the zone offset of 2 hours implied by CEST even though the date it has chosen is not at the time of year where CEST (summer time) is in use. I don’t know whether it just gives you the first Friday of the weekbased year (Friday in week 1 of the year). Friday at 0000 hours at offset GMT+2 equals Thursday at 23 at GMT+1, which is CET.
Next for the formatting, 05 is the date as expected, but lowercase mm means minutes. Since the minutes are 0, you get 00. You got the right year.
Rather than using the outdated classes that give you such surprises, I agree with Sam’s answer that you should use the newer classes in java.time:
ZonedDateTime dt = ZonedDateTime.parse(t,
DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US));
String s = dt.format(DateTimeFormatter.ofPattern("dd.MM.uuuu"));
This code gives you 19.05.2017 as you had expected. One of the good things about the modern classes is, if you try to parse with your original format pattern string, you will get a DateTimeParseException so you will know something is wrong. I certainly prefer an exception over incorrect output.
Another good thing is these classes respect the time zone in the input and use it in the output too (unless you explicitly instruct them otherwise). They will never turn Friday 6 January into Thursday 5 January because of some funny time zone issue.
Your input date is in Central European Summer Time and your date format is a bit wrong. Try
SimpleDateFormat input = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzzz yyyy");
You might want to set the timezone on the output date format in order to get the date in the correct local time.
Ideally you'd move over to use a java.time style as shown here:
https://www.mkyong.com/java/java-convert-date-and-time-between-timezone/
Here's my code:
java.util.Date TODAY = new java.util.Date();
SimpleDateFormat SDF = new SimpleDateFormat( "YYYY-MM-DD" );
System.out.println ( SDF.format( TODAY ) );'
And the result is:
2015-02-33
But today's date is 2015-02-02!
What may be the reason behind this wrong output?
You want to use the yyyy year and dd day of the month.
However, I suggest you migrate to JSR-310 which is built into Java 8 and available for earlier versions of Java. The same code is
System.out.println(LocalDate.now());
prints
2105-02-02
What may be the reason behind this Wrong Output ?
Your assumptions about the date format string are wrong, the output is correct.
y Year
Y Week year
D Day in year
d Day in month
M Month in year
m Minute in hour
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Y Week year will usually give incorrect results around new year. D will give incorrect results from February. So your format appeared fine most of last month.
When format for SimpleDateFormat is specified as follows:
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
the YYYY - means week year,
the MM - means month,
the DD - means day in year.
Week year here is not what you wanted. See what is week year.
Your today's date is 2015-02-02, which means that it is 32 days since the beginning of the year 2015 passed and your are on the 33 day. That is why you get date "2015-02-33".
To mean year (and not week year) and day in month change format to SimpleDateFormat("yyyy-MM-dd");
How do i convert the following String Date into Data format in Java?
"10/01/2012 06:45:23:245946"
I am using the following code
dateFormat = new SimpleDateFormat("MM/dd/yyyy hh24:mm:ss:SSS");
java.util.Date parsedDate = dateFormat.parse("10/01/2012 06:45:23:245946");
And i am getting the following error
java.text.ParseException: Unparseable date: "10/01/2012 06:45:23:245946"
There is no hh24 in SimpleDateFormat, You should be using HH
Your pattern is wrong. Try:
"MM/dd/yyyy HH:mm:ss:SSS"
There is no hh24 in date matching pattern.
The pattern for hour is as follows:
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
See the whole date pattern on SimpleDateFormat javadoc.
You're almost there.
Get rid of the 24 after hh and change it to HH, that should make it work.
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SSS");
Date parsedDate = dateFormat.parse("10/02/2012 06:45:23:245946");
System.out.println(parsedDate);
This will give you an error in time but parse the date successfull, as will all of our answers.
This is fixed by trimming the milliseconds down to 3 digits from 245946 to 245
If you do however want to use 6 digits I would suggest looking into the JodaTime API for more advanced datehandling as JodaTime handles microseconds. But as for java.util.Date, you're out of luck I'm afraid.
Read this bugreport why:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4148168
EDIT: Thanks Jesper for pointing out my bad wording
The 24 in your date format is an invalid format specifier. Remove it. HH is the equivalent of hours on a 24-hour scale.
dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SSS");
I am doing this..
String dateString = "12 Nov 2011 12:00"
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm");
Date date = formatter.parse(dateString);
System.out.println(date.getDay());
this prints out day as 3 ? why is this happening ? how can I print the correct day?
Please read the documentation it is worth learning by that.
date.getDay() prints the day of the week. It should display 6 as that is a saturday, not sure how you got 3 as the result.
date.getDay() returns the day of the week as a zero-indexed numeric. In this case it should be Saturday (6).
Your result of Wednesday (3) suggests you are using a variation of the provided code and perhaps forgotten that the month is zero-indexed. e.g.
Date date = new Date(2011, 11, 12, 24, 0, 0); // month is now December, and time ticks over to Wednesday 13th
System.out.println(date.getDay()); // this would produce 3
I believe you want date.getDate().
If you are looking for a String representation of the day, take a look at this example:
http://www.java-examples.com/formatting-day-week-using-simpledateformat
Even better, check out the Joda-Time library, it is much more intuitive than the classes provided in the Java SDK. A future version of Java may even adopt a new date framework similar to Joda-Time (JSR-310)
The code you showed should print 6, as this date is a Saturday. On my computer that happens. without further information I cannot deduce more. Is this the complete code you execute? You could print the value of date.toString(), that would possibly give some more information.
I want to get the difference between two Java Date objects. I've used Joda-Time library. But the problem is that I'm getting the Days greater difference than that of actual day difference.
Here's my code snippet:
DateFormat formatter = new SimpleDateFormat("mm/dd/yyyy");
Date someDate=new Date();
Date today = Calendar.getInstance().getTime();
try {
someDate = formatter.parse("06/22/2010");
}
catch(ParseException pe) {
System.out.println("Parser Exception");
}
int days = Days.daysBetween(new DateTime(someDate), new DateTime(today)).getDays();
System.out.println(" Days Between " + someDate + " : " + today + " - " + days);
Here's my output:
Days Between Fri Jan 22 00:06:00 IST 2010 : Sun Jul 25 19:27:01 IST 2010 - 184
Here, Why does it takes "06/22/2010" as Jan 22? Does anyone face similar problem?
Help me friends.. Thanx in advance..
It seems like mm refers to minutes, not months, which is MM. Please check here to see the list of appropriate lettering :)
Month is MM
In your case:
DateFormat formatter = new
SimpleDateFormat("MM/dd/yyyy");
Your pattern is slightly defective. mm is parsed as minutes in hour, you're looking for MM which is month of year.
mm => minutes, not months - you need MM for months - that'll resolve your Jan problem!
The other answers correctly solved your specific problem.
LocalDate
But there is a larger solution. If you are starting with only dates, no time-of-day and no time zones, then you should be using the LocalDate class rather than DateTime.
Time Zone
Your code ignores the crucial issue of time zones. Time zones matter even for LocalDate, when trying to determine "today". Do you want today's date in Montréal or in Paris. A new day dawns in Paris earlier. When you omit time zone, you get the JVM’s current default time zone.
Joda-Time Can Parse
Furthermore, let Joda-Time do the parsing. No need to be using java.util.Date & .Calendar at all. Joda-time's formatting characters are almost the same as java.util.Date but not entirely so be sire to consult the doc. In this case it it identical.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate past = formatter.parseLocalDate( "06/22/2010" );
DateTimeZone = DateTimeZone.forID( "America/Montreal" ): // match time zone intended for that input string.
int days = Days.daysBetween( past, LocalDate.now( timeZone ) );