I have a UTC time in long value: 1555415100000L
I used this source code to convert to local time by timezone.
//data.getTime() = 1555415100000L
String timeFormat = "HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
long gmtTime = Long.parseLong(data.getTime()) + TimeZone.getDefault().getRawOffset();
String timeString = sdf.format(new Date(gmtTime));
At GMT+7: timeString = 01:45 (Correct)
But at GMT+6.5: timeString = 00:45 (Incorrect) -> Should be 01:15
Do you have any suggestion to correct time by local ?
A few things:
Manipulating a timestamp by adding or subtracting offsets is never the correct way to convert for time zones, in any language. Always look for APIs that allow you to work with time zone identifiers instead. If you manipulate timestamps, you're deliberately picking a different point in time. That is not the same concept as adjusting for a local time zone.
There are only two time zones in the world that use +6.5. They are Asia/Yangon
(in Myanmar) and Indian/Cocos
(in the Cocos/Keeling Islands). You should use one of those instead.
Your assertion about the local time of that timestamp is incorrect.
1555415100000
corresponds to the UTC time of 2019-04-16T11:45:00.000Z
2019-04-16T18:45:00.000+07:00
(18:45, not 01:45 as you stated)2019-04-16T18:15:00.000+06:30
(18:15, not 01:15 as you stated)You should consider using the java.time
package, introduced with Java 8. On Android, you can use the ThreeTenABP library, a backport of the java.time API for Android.
import java.time.*;
import java.time.format.*;
...
long time = 1555415100000L;
Instant instant = Instant.ofEpochMilli(time);
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Yangon"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
System.out.println(formatter.format(zonedDateTime)); //=> "18:15"
If you really insist on using the older date and time APIs, despite all of their very well documented problems, then you need to set the time zone of your formatter instead of manipulating the timestamp.
import java.util.*;
import java.text.*;
...
long time = 1555415100000L;
long date = new Date(time));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Yangon"));
System.out.println(sdf.format(date); //=> "18:15"