Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert date and time in any timezone to UTC zone

  • this is my date " 15-05-2014 00:00:00 "

  • how to convert IST to UTC i.e( to 14-05-2014 18:30:00)

  • based on from timezone to UTC timezone.

my code is

DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");

formatter.setTimeZone(TimeZone.getTimeZone("IST"));  //here set timezone

System.out.println(formatter.format(date));  
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));  //static UTC timezone

System.out.println(formatter.format(date));  
String str = formatter.format(date);
Date date1  = formatter.parse(str);
System.out.println(date1.toString());
  • if user enter same date from any zone then will get UTC time(ex: from Australia then 15-05-2014 00:00:00 to 14-05-2014 16:00:00)

  • please any suggestions.

like image 581
user3599212 Avatar asked Jun 16 '14 09:06

user3599212


Video Answer


1 Answers

You cannot "convert that date values" to other timezones or UTC. The type java.util.Date does not have any internal timezone state and only refers to UTC by spec in a way which cannot be changed by user (just counting the milliseconds since UNIX epoch in UTC timezone leaving aside leapseconds).

But you can convert the formatted String-representation of a java.util.Date to another timezone. I prefer to use two different formatters, one per timezone (and pattern). I also prefer to use "Asia/Kolkata" in your case because then it will universally works (IST could also be "Israel Standard Time" which will be interpreted differently in Israel):

DateFormat formatterIST = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterIST.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // better than using IST
Date date = formatterIST.parse("15-05-2014 00:00:00");
System.out.println(formatterIST.format(date)); // output: 15-05-2014 00:00:00

DateFormat formatterUTC = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // UTC timezone
System.out.println(formatterUTC.format(date)); // output: 14-05-2014 18:30:00

// output in system timezone using pattern "EEE MMM dd HH:mm:ss zzz yyyy"
System.out.println(date.toString()); // output in my timezone: Wed May 14 20:30:00 CEST 2014
like image 103
Meno Hochschild Avatar answered Oct 27 '22 03:10

Meno Hochschild