2013-04-09 72 views
1

我的日期格式类似于“MM-dd-yyyy hh:mm”它不是当前日期,我必须将此日期 发送到服务器,但在发送它之前需要将此日期更改为GMT格式,但是当我通过关注代码:如何转换“MM-dd-yyyy hh:mm”字符串日期格式为GMT格式?

private String[] DateConvertor(String datevalue) 
     { 
      String date_value[] = null; 
      String strGMTFormat = null; 
      SimpleDateFormat objFormat,objFormat1; 
      Calendar objCalendar; 
      Date objdate1,objdate2; 
      if(!datevalue.equals("")) 
      { 
      try 
      { 
      //Specify your format 
       objFormat1 = new SimpleDateFormat("MM-dd-yyyy,HH:mm"); 
       objFormat1.setTimeZone(Calendar.getInstance().getTimeZone()); 

       objFormat = new SimpleDateFormat("MM-dd-yyyy,HH:mm"); 
       objFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 

      //Convert into GMT format 
      //objFormat.setTimeZone(TimeZone.getDefault());//); 
      objdate1=objFormat1.parse(datevalue); 
      // 
      //objdate2=objFormat.parse(datevalue); 


      //objFormat.setCalendar(objCalendar); 
      strGMTFormat = objFormat.format(objdate1.getTime()); 
      //strGMTFormat = objFormat.format(objdate1.getTime()); 
      //strGMTFormat=objdate1.toString(); 
      if(strGMTFormat!=null && !strGMTFormat.equals("")) 
      date_value = strGMTFormat.split(","); 
      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
       e.toString(); 
      } 
      finally 
      { 
      objFormat = null; 
      objCalendar = null; 
      } 
      } 
      return date_value; 

     } 

其要求的格式不会改变,我已经通过上面的代码中第一次尝试尝试获取当前的时区和后试图改变字符串日期到该时区后转换GMT。 任何人都可以引导我。

在此先感谢。

回答

2

请尝试下面的代码。第一个sysout打印日期对象,它挑选默认的OS时区,即我的情况下的IST。将日期转换为GMT时区后,第二个sysout以所需格式打印日期。

如果您知道日期字符串的时区,请在格式化程序中进行设置。我认为你需要格林尼治标准时间的同一日期格式。

SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy,HH:mm"); 

Date date = format.parse("01-23-2012,09:40"); 
System.out.println(date); 

format.setTimeZone(TimeZone.getTimeZone("GMT")); 
System.out.println(format.format(date)); 
2

你需要使用的时区的getRawOffset()方法:

Date localDate = Calendar.getInstance().getTime(); 
TimeZone tz = TimeZone.getDefault(); 
Date gmtDate = new Date(date.getTime() - tz.getRawOffset()); 

返回的时间以毫秒计算添加到UTC在这个时间段来获得标准的时间。由于此值不受夏令时的影响,因此称为原始偏移量。

如果你要考虑DST,以及如果你是对上一个夏天的时间变化的边缘会(你可能想这;-))

if (tz.inDaylightTime(ret)) { 
    Date dstDate = new Date(gmtDate.getTime() - tz.getDSTSavings()); 

    if (tz.inDaylightTime(dstDate) { 
     gmtDate = dstDate; 
    } 
} 

需要最后检查,例如,通过转换回到标准时间。

希望帮助,

-Hannes

相关问题