date format parses the 12th hour value (hh) to 00
date format parses the 12th-hour value (hh) to 00 while applying the format as "yyyy-MM-dd'T'hh:mm:ss" but it does not parse the 13th hour to 1 PM. PFB the sample code piece.
Date testDate = DateUtil.parse("yyyy-MM-dd'T'hh:mm:ss", "2010-07-09T12:50:58");
can you please let me know why t开发者_开发技巧his is converting so?
You should use HH
instead of hh
. The former is for 24-hour clock, the latter for a 12-hour clock.
See the javadoc for SimpleDateFormat.
EDIT: Note that the problem may be at the other end too. To get the hour from a java.util.Date
, you can set it on a Calendar
object and call get(Calendar.HOUR_OF_DAY)
. Note that get(Calendar.HOUR)
will give you the 12-hour rather than the 24-hour.
DateFormat inputFormatter = new SimpleDateFormat(
"yyyy-MM-dd'T'hh:mm:ss");
Date date = inputFormatter.parse("2010-07-09T13:50:58");
DateFormat outputFormatter = new SimpleDateFormat(
"yyyy-MM-dd'T'hh:mm:ss a");
System.out.println(outputFormatter.format(date));
The output is:
2010-07-09T01:50:58 PM
It reads in 13 fine, and outputs 01 (PM).
As you are reading a time with timezone and printing with your locale, the system transforms time to your local in Uruguay.
You need to create a calendar with custom locale and timezone in order to keep it consistent:
public static void main(String[] args) throws ParseException {
String dateStr = "Tue, 04 Aug 2015 12:09:10 GMT";
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
Date d = format.parse(dateStr);
System.out.println("The current time is: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"), Locale.ENGLISH);
cal.setTime(d);
System.out.println("The current time is: " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));
}
精彩评论