Java: How to Convert a Utc Timestamp to Local Time

Java: How do you convert a UTC timestamp to local time?

Date has no timezone and internally stores in UTC. Only when a date is formatted is the timezone correction applies. When using a DateFormat, it defaults to the timezone of the JVM it's running in. Use setTimeZone to change it as necessary.

DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

Date date = utcFormat.parse("2012-08-15T22:56:02.038Z");

DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
pstFormat.setTimeZone(TimeZone.getTimeZone("PST"));

System.out.println(pstFormat.format(date));

This prints 2012-08-15T15:56:02.038

Note that I left out the 'Z' in the PST format as it indicates UTC. If you just went with Z then the output would be 2012-08-15T15:56:02.038-0700

How can I get the UTC-converted Java timestamp of current local time?

You can do it like this :

LocalDateTime localDateTime = Instant.now().atOffset(ZoneOffset.UTC).toLocalDateTime();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
System.out.println(localDateTime.format(formatter));

Java convert UTC timestamp to local DateTime

Try this is working with me

public  String getDateCurrentTimeZone(long timestamp) {
try{
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
return sdf.format(currenTimeZone);
}catch (Exception e) {
}
return "";
}

Convert UTC date to current timezone

it print GMT+02 because this is your "local" timezone.
if you want to print the date without timezone information, use SimpleDateFormat to format the date to you liking.

edit : adding the code example (with your variable 'myDate')

SimpleDateFormat inputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
inputSDF.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = inputSDF.parse("2016-09-25 17:26:12");
//
SimpleDateFormat outputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(outputSDF.format(myDate));
System.out.println(TimeZone.getDefault().getID());

yield on the (my) console (with my local timezone).

2016-09-25 19:26:12
Europe/Paris

How to convert a UTC timestamp to local day, hour, minute in Java?

You can use java.util.Calendar for this. It offers a setTimeZone() method (which is by the way superfluous since it by default already picks the system default timezone).

long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);

int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

If you'd like to present it in a human readable date string, then I'd suggest SimpleDateFormat for this.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25

(the output is correct as per my timezone GMT-4)

How to convert UTC time into local time in Java?

Create a new Date from your milliseconds since epoch. Then use a DateFormat to format it in your desired timezone.

Date date = new Date(1352437114052L);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(format.format(date));

How can I get the current date and time in UTC or GMT in Java?

java.util.Date has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?

To be precise: the value within a java.util.Date is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date is the same around the world at any particular instant, regardless of local time zone.

I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone, or a SimpleDateFormat instance, which, by default, also uses local timezone.

If this isn't the problem, please post some sample code.

I would, however, recommend that you use Joda-Time anyway, which offers a much clearer API.

How to convert UTC timestamp to device local time in android

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);


Related Topics



Leave a reply



Submit