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);
(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.).
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.
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.
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
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With