SimpleDateFormat ignoring month when parsing
The following code is giving me the parsed date as "Wed Jan 13 00:00:00 EST 2010" instead of "Wed Jun 13 00:00:00 EST 2010". Any ideas much appreciated.
SimpleDateFormat sf = new SimpleDateFormat("yyyy-mm-dd'T'HH:mm:ss");
String str = "2010-06-13T00:00:00";
Date date = sf.parse(str);
System.out.println(" Date " + date.toString());
Solution 1:
Try:
"yyyy-MM-dd'T'HH:mm:ss"
MM
means month. mm
means minutes. See the documentation for SimpleDateFormat
for more details of the supported date and time patterns.
Solution 2:
The problem is that you're using 'mm' as month and 'mm' represents minutes. Below is all date formats available, read more doc here.
Symbol Meaning Kind Example
D day in year Number 189
E day of week Text E/EE/EEE:Tue, EEEE:Tuesday, EEEEE:T
F day of week in month Number 2 (2nd Wed in July)
G era designator Text AD
H hour in day (0-23) Number 0
K hour in am/pm (0-11) Number 0
L stand-alone month Text L:1 LL:01 LLL:Jan LLLL:January LLLLL:J
M month in year Text M:1 MM:01 MMM:Jan MMMM:January MMMMM:J
S fractional seconds Number 978
W week in month Number 2
Z time zone (RFC 822) Time Zone Z/ZZ/ZZZ:-0800 ZZZZ:GMT-08:00 ZZZZZ:-08:00
a am/pm marker Text PM
c stand-alone day of week Text c/cc/ccc:Tue, cccc:Tuesday, ccccc:T
d day in month Number 10
h hour in am/pm (1-12) Number 12
k hour in day (1-24) Number 24
m minute in hour Number 30
s second in minute Number 55
w week in year Number 27
G era designator Text AD
y year Number yy:10 y/yyy/yyyy:2010
z time zone Time Zone z/zz/zzz:PST zzzz:Pacific Standard
Solution 3:
Modern answer:
String str = "2010-06-13T00:00:00";
LocalDateTime dateTime = LocalDateTime.parse(str);
System.out.println("Date-time " + dateTime);
Output:
Date-time 2010-06-13T00:00
I am using and recommending java.time
, the modern Java date and time API. We don’t even need an explicit formatter for parsing. This is because your string is in ISO 8601 format, the international standard that the java.time
classes parse as their default. java.time
came out in 2014.
While in 2010 when this question was asked, SimpleDateFormat
was what we had for parsing dates and times, that class is now considered long outdated, fortunately, because it was also troublesome.
In case your string contained only a date without time of day, use the LocalDate
class in quite the same manner (this was asked in a duplicate question).
String dateStr = "2018-05-23";
LocalDate date2 = LocalDate.parse(dateStr);
System.out.println(date2);
2018-05-23
Link: Oracle tutorial: Date Time explaining how to use java.time
.