Search code examples
javaandroidandroid-date

Hours and minutes from date in android


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?


Solution

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