简体   繁体   中英

Dateformat adds extra 30 minutes to time

I'm using this Android code for converting milliseconds to mm:ss.SS format but in result dateformat adds 30 extra minutes in date.

        Date date = new Date(millis);
        DateFormat dateFormat= new SimpleDateFormat("mm:ss.SS", Locale.US);
        best.add(dateFormat.format(date));\

Actually I want to convert milliseconds to m:ss.SS format. Is there any other best way to achieve this?

Thanks in advance.

to set the TImezone :

dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

My Guess...if you are living in a GMT+30 min time zone and unless you specify a different one, your formatter will pick your current one, so it considers 0 hours as GMT and as you are in GMT+30 Min, it outputs + 30 Minutes...

To get timezone from user current place you can use:

 TimeZone tz = TimeZone.getDefault();
System.out.println("TimeZone   "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());

then you can set the Timezone in dateformat.

it will return you the timezone like " IST "

Also you can try the following code to find the GMT offset of a Timezone:

 public String getCurrentTimezoneOffset() {

    TimeZone tz = TimeZone.getDefault();  
    Calendar cal = GregorianCalendar.getInstance(tz);
    int offsetInMillis = tz.getOffset(cal.getTimeInMillis());

    String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
    offset = "GMT"+(offsetInMillis >= 0 ? "+" : "-") + offset;

    return offset;
}

it will return Timezone like: GMT+05:30 this format

By using timezone you can find accurate time in all devices..

see this also:https://developer.android.com/reference/java/util/TimeZone.html

您可以将代码更改为:

DurationFormatUtils.formatDuration(millis, "mm:ss.SS");

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