0

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?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
Viraj
  • 4,641
  • 5
  • 31
  • 66
  • 1
    Check this http://stackoverflow.com/questions/6567923/timezone-conversion – Samuel Robert Sep 26 '16 at 05:37
  • 1
    The timestamp will be the same. A timestamp doesn't have any timezone: 2016-09:26T12:00 UTC is the same instant as 2016-09:26T14:00 in Paris. The timezone is relevant when you display the timestamp as something readable by a human. – JB Nizet Sep 26 '16 at 06:14

2 Answers2

2

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.

Wojciech Kazior
  • 1,238
  • 9
  • 15
0

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
Riddhi Gohil
  • 1,690
  • 16
  • 17