Hours and minutes from date in android

2019-07-17 05:40发布

I have java util date as Thu Feb 28 15:35:00 GMT+00:00 2013

How to convert it to HH:MM.

I am trying to do this via below snippet:

SimpleDateFormat formatter = new SimpleDateFormat("HH:MM");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
        return formatter.format(objDate);

Its giving right result for dd mmm but always giving minutes as 02 for HH:MM

Please suggest me what is wrong in this function?

2条回答
beautiful°
2楼-- · 2019-07-17 06:01

use

String str ="Thu Feb 28 15:35:00 GMT+00:00 2013";

SimpleDateFormat formatter_from = new SimpleDateFormat("EEE MMM dd hh:mm:ss ZZ yyyy");
SimpleDateFormat formatter_to = new SimpleDateFormat("hh:mm");

try {
    java.util.Date d = formatter_from.parse(str);

    System.out.println(formatter_to.format(d));

} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
查看更多
Fickle 薄情
3楼-- · 2019-07-17 06:07

MM is the month value in SimpleDateFormat. You want mm. Note that using HH will give you the 24 hour clock (00-23)... you can use hh for the 12 hour clock (01-12) but you probably also want the am/pm designator in that case.

See the documentation for SimpleDateFormat for more details of the various format specifiers available.

Also note that for internationalization purposes, you might be better off with:

DateFormat formatter = DateFormat.getTimeInstance(DateFormat.SHORT, locale);

... so that it will use the appropriate "short time format" for the given locale. That's appropriate if this is for display (human-readable) purposes; for computer-readable formats, it's fine to create a custom format but I'd recommend explicitly using Locale.US to avoid getting different calendars and format symbols (e.g. the time separator).

查看更多
登录 后发表回答