简体   繁体   中英

SimpleDateFormat parse exception for Time

DateFormat FORMAT_TIME_AM = new SimpleDateFormat("hh:mm");//works

If I use this code, everything works fine, but when I insert an "a" to display the AM/PM in the end, a parsing exception is raised.

DateFormat FORMAT_TIME_AM = new SimpleDateFormat("hh:mm a");//does not works

Here is the error:

com.finalagenda W/System.err java.text.ParseException: Unparseable date: "2:11" (at offset 4) com.finalagenda W/System.err﹕ at java.text.DateFormat.parse(DateFormat.java:579)

Any thoughts?

In SimpleDateFormat , HH and hh are different. HH from 0 to 23 for 24 hours format and hh from 1 to 12 (AM/PM) 12 hours format.

"HH:mm" -> 13:30 is "hh:mm a" -> 01:30 PM

Okay guys I just fixed, just added "AM" to the end of my String time and it automatically changes to "PM" if necessary. Thanks for everything, hope this helps anyone else.

The code below works fine here. Could you please provide part of your code?

public static void main(String args[])
{
    DateFormat FORMAT_TIME_AM = new SimpleDateFormat("hh:mm a");
    System.out.println(FORMAT_TIME_AM.format(new Date()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM