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);
The code in your example looks fine at first glance. BTW, if the server timestamp is in UTC (i.e. it's an epoch timestamp) then you should not have to apply the current timezone offset. In other words if the server timestamp is in UTC then you can simply get the difference between the server timestamp and the system time (System.currentTimeMillis()
) as the system time is in UTC (epoch).
I would check that the timestamp coming from your server is what you expect. If the timestamp from the server does not convert into the date you expect (in the local timezone) then the difference between the timestamp and the current system time will not be what you expect.
Use Calendar
to get the current timezone. Initialize a SimpleDateFormatter
with the current timezone; then log the server timestamp and verify if it's the date you expect:
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
/* debug: is it local time? */
Log.d("Time zone: ", tz.getDisplayName());
/* date formatter in local timezone */
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(tz);
/* print your timestamp and double check it's the date you expect */
long timestamp = cursor.getLong(columnIndex);
String localTime = sdf.format(new Date(timestamp * 1000)); // I assume your timestamp is in seconds and you're converting to milliseconds?
Log.d("Time: ", localTime);
If the server time that is printed is not what you expect then your server time is not in UTC.
If the server time that is printed is the date that you expect then you should not have to apply the rawoffset to it. So your code would be simpler (minus all the debug logging):
long timestamp = cursor.getLong(columnIndex);
Log.d("Server time: ", timestamp);
/* log the device timezone */
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Log.d("Time zone: ", tz.getDisplayName());
/* log the system time */
Log.d("System time: ", System.currentTimeMillis());
CharSequence relTime = DateUtils.getRelativeTimeSpanString(
timestamp * 1000,
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS);
((TextView) view).setText(relTime);
int offset = TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings();
long now = 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;
}
I did it using Extension Functions
in kotlin
fun String.toDate(dateFormat: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone = TimeZone.getTimeZone("UTC")): Date {
val parser = SimpleDateFormat(dateFormat, Locale.getDefault())
parser.timeZone = timeZone
return parser.parse(this)
}
fun Date.formatTo(dateFormat: String, timeZone: TimeZone = TimeZone.getDefault()): String {
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
formatter.timeZone = timeZone
return formatter.format(this)
}
Usage:
"2018-09-10 22:01:00".toDate().formatTo("dd MMM yyyy")
Output: "11 Sep 2018"
Note:
Ensure the proper validation.
I have do something like this to get date in local device timezone from UTC time stamp.
private long UTC_TIMEZONE=1470960000;
private String OUTPUT_DATE_FORMATE="dd-MM-yyyy - hh:mm a"
getDateFromUTCTimestamp(UTC_TIMEZONE,OUTPUT_DATE_FORMATE);
Here is the function
public String getDateFromUTCTimestamp(long mTimestamp, String mDateFormate) {
String date = null;
try {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(mTimestamp * 1000L);
date = DateFormat.format(mDateFormate, cal.getTimeInMillis()).toString();
SimpleDateFormat formatter = new SimpleDateFormat(mDateFormate);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat(mDateFormate);
dateFormatter.setTimeZone(TimeZone.getDefault());
date = dateFormatter.format(value);
return date;
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
Result :
12-08-2016 - 04:30 PM
Hope this will work for others.
Local to UTC
DateTime dateTimeNew = new DateTime(date.getTime(),
DateTimeZone.forID("Asia/Calcutta"));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String datetimeString = dateTimeNew.toString("yyyy-MM-dd HH:mm:ss");
long milis = 0;
try {
milis = simpleDateFormat.parse(datetimeString).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
This may help some one with same requirement
private String getDate(long time){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
String dateString = formatter.format(new Date(time));
String date = ""+dateString;
return date;
}