问题
How do i parse the following date string in a valid java date? I am having trouble parsing the timezone.
"2013-10-10 10:43:44 GMT+5"
I am using the following method for parsing the date. It works well when the timezone is like "GMT+05:00" but fails to parse the above string even if i use different combinations of z, Z, X
public static Date convertStringWithTimezoneToDate(String dateString) {
if (dateString == null) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzzz");
Date convertedDate = null;
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return convertedDate;
}
回答1:
Your date format is non-standard. The time zone must respect the syntax given in the documentation:
GMTOffsetTimeZone: GMT Sign Hours : Minutes Sign: one of + - Hours: Digit Digit Digit Minutes: Digit Digit Digit: one of 0 1 2 3 4 5 6 7 8 9
This code the transform your format into a standard one and construct a Java date object.
public static Date convertStringWithTimezoneToDate(String dateString) {
if (dateString == null) {
return null;
}
dateString += ":00";
System.out.println(dateString);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date convertedDate = null;
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return convertedDate;
}
P.S.: Only one z is needed in the pattern string.
来源:https://stackoverflow.com/questions/19288687/timezone-parsing-issue-in-java