0

I have written a code to convert date into UTC based on timezone I provided. Also I have set -Duser.timezone=UTC.

public static java.util.Date getUtcDateFromTimezone(java.util.Date date,TimeZone timezone)
{
//  java.util.Date utcDate=null;
    Calendar calendar=Calendar.getInstance(timezone);
    calendar.setTime(date);

    Calendar utcCalendar=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    utcCalendar.setTime(calendar.getTime());        
    return utcCalendar.getTime();
}

How can I convert to UTC based on particular timezone?

Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55
Vishvesh Phadnis
  • 2,448
  • 5
  • 19
  • 35
  • 1
    Are you by any chance using Java 8? There is a new and improved time api. Otherwise, if you are doing a lot of these things Joda Time could help. – ftr Oct 08 '14 at 09:34

1 Answers1

0

Hope this example can help you:

public static String convertLocalTimeToUTC(String saleTimeZone, String p_localDateTime) throws Exception{

  String dateFormateInUTC="";
  Date localDate = null;
  String localTimeZone ="";
  SimpleDateFormat formatter;
  SimpleDateFormat parser;
  localTimeZone = saleTimeZone;

  //create a new Date object using the timezone of the specified city
  parser = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
  parser.setTimeZone(TimeZone.getTimeZone(localTimeZone));
  localDate = parser.parse(p_localDateTime);
  formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z'('Z')'");
  formatter.setTimeZone(TimeZone.getTimeZone(localTimeZone));
  System.out.println("convertLocalTimeToUTC: "+saleTimeZone+": "+" The Date in the local time zone " +   formatter.format(localDate));

  //Convert the date from the local timezone to UTC timezone
  formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
  dateFormateInUTC = formatter.format(localDate);
  System.out.println("convertLocalTimeToUTC: "+saleTimeZone+": "+" The Date in the UTC time zone " +  dateFormateInUTC);

 return dateFormateInUTC;
 }

  public static void main(String arg[]) throws Exception
    {

        convertLocalTimeToUTC("EST", "12-03-2013 10:30:00");
        convertLocalTimeToUTC("PST", "12-03-2013 10:30:00");
    }

This was taken from here

ftr
  • 2,105
  • 16
  • 29
Imran
  • 429
  • 9
  • 23