java.time
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.
What went wrong in your code?
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).
Links