Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert UTC timestamp to device local time in android

I need to convert the UTC time stamp that i get from the server to local device time. currently i get 5 hrs difference in my time. for example when i post to server the post time says 5 hours ago instead of a second ago. How to fix this issue. thanks

Below is the code that i do

long timestamp = cursor.getLong(columnIndex);             CharSequence relTime = DateUtils                     .getRelativeTimeSpanString(timestamp * 1000                             + TimeZone.getDefault().getRawOffset(),                             System.currentTimeMillis(),                             DateUtils.MINUTE_IN_MILLIS);             ((TextView) view).setText(relTime); 
like image 649
cavallo Avatar asked Feb 13 '13 12:02

cavallo


People also ask

How do I convert UTC timestamp to local time?

(GMT-5:00) Eastern Time (US & Canada)Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).

How do I set UTC time zone on Android?

On a current Android device, tap the Clock app, tap the Globe icon (bottom of the screen), then search for UTC and tap the UTC result. On a current iOS device, tap the Clock app, tap World Clock, then + (in the upper-right corner), search for UTC, then tap the UTC result.

How is UTC local time calculated?

Examples of how to convert UTC to your local time To convert 18:00 UTC (6:00 p.m.) into your local time, subtract 6 hours, to get 12 noon CST. During daylight saving (summer) time, you would only subtract 5 hours, so 18:00 UTC would convert to 1:00 p.m CDT. Note that the U.S. uses a 12-hour format with a.m. and p.m.


2 Answers

Java:

int offset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings(); long now = System.currentTimeMillis() - offset; 

Kotlin:

val offset: Int = TimeZone.getDefault().rawOffset + TimeZone.getDefault().dstSavings val now: Long = System.currentTimeMillis() - offset 
like image 78
prgDevelop Avatar answered Sep 17 '22 00:09

prgDevelop


Converting a date String of the format "2011-06-23T15:11:32" to our time zone.

private String getDate(String ourDate) {     try     {         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");         formatter.setTimeZone(TimeZone.getTimeZone("UTC"));         Date value = formatter.parse(ourDate);          SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy HH:mm"); //this format changeable         dateFormatter.setTimeZone(TimeZone.getDefault());         ourDate = dateFormatter.format(value);          //Log.d("ourDate", ourDate);     }     catch (Exception e)     {         ourDate = "00-00-0000 00:00";     }   return ourDate; } 
like image 45
madhu527 Avatar answered Sep 18 '22 00:09

madhu527