有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将日期从不同时区转换为UTC

我已经编写了一个代码,根据我提供的时区将日期转换为UTC。 我还有布景-杜瑟。时区=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();
}

如何根据特定时区转换为UTC


共 (1) 个答案

  1. # 1 楼答案

    希望这个例子能帮助你:

    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");
        }
    

    这是取自here