Date and Time Conversion has always been my weak link. I have the following values in string format:
Now I need to covert this date, for which I already know the timezone, to UTC date.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With