Hours and minutes from date in android

坚强是说给别人听的谎言 提交于 2019-12-24 01:02:05

问题


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?


回答1:


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).




回答2:


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();
}


来源:https://stackoverflow.com/questions/15132878/hours-and-minutes-from-date-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!