Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date with known timezone to UTC date

Date and Time Conversion has always been my weak link. I have the following values in string format:

  1. String date="2015-08-21 03:15" and timezone for this date is
  2. String timeZone="GMT+05:30";

Now I need to covert this date, for which I already know the timezone, to UTC date.

like image 519
Hitesh Bhutani Avatar asked Aug 20 '15 06:08

Hitesh Bhutani


2 Answers

If you are given time in "GMT+05:30" timezone next code will convert it to UTC timezone:

String strDate = "2015-08-21 03:15";
String timeZone="GMT+05:30";
String format = "yyyy-MM-dd HH:mmz";
SimpleDateFormat formatter = new SimpleDateFormat(format);
Date dateStr = formatter.parse(strDate+timeZone);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = formatter.format(dateStr);
System.out.println("UTC datetime is: "+formattedDate);
like image 86
Alexander Stepchkov Avatar answered Sep 24 '22 21:09

Alexander Stepchkov


You can try like this:

Approach 1: Using Java Date:

//Your input date string
String date="2015-08-21 03:15";

// date format your string
String format = "yyyy-MM-dd HH:mm";

//Create SimpleDateFormat instance
SimpleDateFormat sdf = new SimpleDateFormat(format);

// Convert Local Time to UTC 
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

//parse your input date string to UTC date
Date gmtTime = new Date(sdf.parse(date));

Approach 2: Using Joda time (recommended)

String dateString = "2015-08-21 03:15:00+5:30";

String pattern = "yyyy-MM-dd HH:mm:ssZ";

DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);

DateTime dateTime = dtf.parseDateTime(dateString);

System.out.println(dateTime);
like image 23
Garry Avatar answered Sep 25 '22 21:09

Garry