0

I have tried below code to convert the local date-time to a UTC date-time. But they are coming as same. I think I am missing something here. Can anyone please help me how can I get the UTC date time from local datetime 10/15/2013 09:00 AM GMT+05:30. This date time string I get from a outer system so if needed I can change the format.

SimpleDateFormat outputFormatInUTC = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa z");
String startDateTime = "10/15/2013 09:00 AM GMT+05:30";
Date utcDate = outputFormatInUTC.parse(startDateTime);
A Paul
  • 8,113
  • 3
  • 31
  • 61

3 Answers3

0

Just set TimeZone:

SimpleDateFormat outputFormatInUTC = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa z");
String startDateTime = "10/15/2013 09:00 AM GMT+05:30";
outputFormatInUTC.setTimeZone(TimeZone.getTimeZone("UTC"));  
Date utcDate = outputFormatInUTC.parse(startDateTime);
String timeInUTC = outputFormatInUTC.format(utcDate);
System.out.println(timeInUTC);

Output:

10/15/2013 03:30 AM UTC
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
  • Thank you for your reply. Here first I am getting the date object then again getting the date as string so now if I need a date object I again have to transfer this string to a date object. Am I correct? If yes, is there any better way of doing this? – A Paul Dec 24 '13 at 06:11
  • Not at all, we first set SimpleDateFormat - > configure time zone -> parse string date -> extract proper String date based on DateFormat. – Maxim Shoustin Dec 24 '13 at 06:24
  • So now I have the date string in UTC. How can I transfer it to a date. – A Paul Dec 24 '13 at 07:10
0

Try this:

    SimpleDateFormat outputFormatInUTC = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa z");
    System.out.println(new Date()); //prints local date-time
    outputFormatInUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println(outputFormatInUTC.format(new Date())); //prints UTC date-time
Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
0

ISO 8601 Format

Yes, if you can change the format of the string, you should. An international standard exists for this very purpose: ISO 8601. Like this 2013-12-26T21:19:39+00:00 or this 2013-12-26T21:19Z.

Joda-Time

Avoid using java.util.Date/Calendar classes. They are notoriously bad. Java 8 supplants them with new java.time.* JSR 310 classes. In the meantime, you can use the Joda-Time library which inspired JSR 310.

My example code below uses Joda-Time 2.3 running in Java 7 on a Mac.

Example Code

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

String string = "10/15/2013 09:00 AM GMT+05:30";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy hh:mm aaa zZ" );
DateTime dateTime = formatter.parseDateTime( string );
System.out.println( "dateTime: " + dateTime );

When run…

dateTime: 2013-10-15T03:30:00.000Z
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154