Reputation: 347
I am trying to parse 14th March 2011 to a date in Java for a time converter application... I get 26th Dec 2010... Please help.
import java.util.*;
import java.text.*;
class date {
public static void main(String[] args) {
try {
String timestampOrig = "11/03/14,15:00:00";
SimpleDateFormat inFormat = new SimpleDateFormat("YY/MM/dd','HH:mm:ss");
Date parseDate = inFormat.parse(timestampOrig);
System.out.println("parsed date: " + parseDate.toString());
}
catch(ParseException pe){
}
}
}
output:
parsed date: Sun Dec 26 15:00:00 EST 2010
Upvotes: 1
Views: 734
Reputation: 86276
I am providing the modern answer using java.time, the modern Java date and time API (since March 2014).
DateTimeFormatter inFormat = DateTimeFormatter.ofPattern("uu/MM/dd,HH:mm:ss");
String timestampOrig = "11/03/14,15:00:00";
LocalDateTime parsedDateTime = LocalDateTime.parse(timestampOrig, inFormat);
System.out.println("parsed date: " + parsedDateTime.toString());
Output is:
parsed date: 2011-03-14T15:00
I recommend you don’t use SimpleDateFormat
and Date
. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use LocalDateTime
and DateTimeFormatter
, both from java.time, the modern Java date and time API. The modern API is so much nicer to work with. And BTW would throw an exception if you tried with YY
for year, which I find somewhat more helpful for catching your error.
The quotes around the comma in the format pattern string are optional. I know that the documentation recommends them, but I find the format pattern string more readable without them, so left them out.
Uppercase Y
in the format patterns string is for week based year and only useful with a week number. Apperently SimpleDateFormat
wasn’t able to combine your specified month and day of month with the week based year of 2011 and instead just took the first day of the week-based year (this is typical behaviour of SimpleDateFormat
, giving you a result that cannot be but wrong and pretending all is well). Assuming your locale is American or similar, week 1 is the week that contains January 1 and begins on the Sunday of the same week, therefore in this case the last Sunday of the previous year, December 26, 2010.
With java.time you may use either lowercase y
or u
for year. The subtle difference is explained in the question linked to at the bottom. In any case a two-digit year is interpreted into the range from year 2000 through 2099 (there are ways to control the interpretation if you need to).
uuuu
versus yyyy
in DateTimeFormatter
formatting pattern codes in Java?Upvotes: 1
Reputation: 328618
YY
should be yy
(in lower case). You can find the list of available characters and their meaning in the documentation.
Out of curiosity, more information about YY
, which is for week year, here (not 100% sure what it is to be honest).
Upvotes: 3