I want to convert this GMT time stamp to GMT+13:
2011-10-06 03:35:05
I have tried about 100 different combinations of DateFormat, TimeZone,
For me, the simplest way to do that is:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));
//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));
We can handle this by using offset value
public static long convertDateTimeZone(long lngDate, String fromTimeZone,
String toTimeZone){
TimeZone toTZ = TimeZone.getTimeZone(toTimeZone);
Calendar toCal = Calendar.getInstance(toTZ);
TimeZone fromTZ = TimeZone.getTimeZone(fromTimeZone);
Calendar fromCal = Calendar.getInstance(fromTZ);
fromCal.setTimeInMillis(lngDate);
toCal.setTimeInMillis(fromCal.getTimeInMillis()
+ toTZ.getOffset(fromCal.getTimeInMillis())
- TimeZone.getDefault().getOffset(fromCal.getTimeInMillis()));
return toCal.getTimeInMillis();
}
Test Code snippet:
System.out.println(new Date().getTime())
System.out.println(convertDateTimeZone(new Date().getTime(), TimeZone
.getDefault().getID(), "EST"));
Output: 1387353270742 1387335270742
The solution is actually quite simple (pure, simple Java):
System.out.println(" NZ Local Time: 2011-10-06 03:35:05");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localNZ = LocalDateTime.parse("2011-10-06 03:35:05",formatter);
ZonedDateTime zonedNZ = ZonedDateTime.of(localNZ,ZoneId.of("+13:00"));
LocalDateTime localUTC = zonedNZ.withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime();
System.out.println("UTC Local Time: "+localUTC.format(formatter));
OUTPUT IS:
NZ Local Time: 2011-10-06 03:35:05
UTC Local Time: 2011-10-05 14:35:05
To find duration or time interval with two different time zone
import org.joda.time.{DateTime, Period, PeriodType}
val s1 = "2019-06-13T05:50:00-07:00"
val s2 = "2019-10-09T11:30:00+09:00"
val period = new Period(DateTime.parse(s1), DateTime.parse(s2), PeriodType dayTime())
period.getDays
period.getMinutes
period.getHours
output period = P117DT13H40M
days = 117
minutes = 40
hours = 13