简体   繁体   中英

How to convert timestamp to different timezone

I have a timestamp taken as below coming to my server.

Date date = new Date();
long timestamp = date.getTime();

This is generated from different timezone and I only have the above long value. I need to convert this time to different timezone. I tried following way but still it shows the local time.

// Convert to localdatetime using local time zone
LocalDateTime ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp),
            ZoneId.systemDefault());

// Convert time to required time zone. 
ZoneId est5EDT = ZoneId.of("EST5EDT");
ZonedDateTime est5EDTTime = ldt.atZone(est5EDT);
System.out.println("EST5EDT : " + est5EDTTime);

Once successfully converted the time I need to get timestamp of that time. How to do this?

You can convert a timezone or a format of the timestamp while you are printing it. There is no need to do anything if you just want to store timestamps or compare them.

This can be done using joda time as well, here is my code :

import java.text.SimpleDateFormat;
import org.joda.time.DateTimeZone;


public class TimeTest{

private static final String DATE_FORMAT = "dd MMM yyyy HH:mm:ss";

private Date dateToTimeZone(Date tempDate, String timeZoneVal) throws ParseException{
            //timeZoneVal -> -8:00, 05:30, .....
            String string = timeZoneVal;
            String[] parts = string.split(":");
            String part1 = parts[0]; 
            String part2 = parts[1];

            int hoursOffset = Integer.parseInt(part1);
            int minutesOffset = Integer.parseInt(part2);

            DateTimeZone timeZone = DateTimeZone.forOffsetHoursMinutes(hoursOffset, minutesOffset);

            String gmtDate = tempDate.toGMTString();

            SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
            dateFormat.setTimeZone(timeZone.toTimeZone());

            return dateFormat.parse(gmtDate);       

        }
}

Output:

  1. tempDate -> Mon Oct 10 00:00:00
  2. gmtDate -> 9 Oct 2016 18:30:00
  3. parsed date in timeZone "-08:00" -> Mon Oct 10 08:00:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM