如何转换" MM-dd-yyyy hh:mm"字符串日期格式为GMT格式?

时间:2013-04-09 04:11:42

标签: java android

我的日期格式就像“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;

        }

它没有改变所需的格式,我已尝试通过上面的代码首先尝试获取当前timeZone,然后尝试在转换GMT之后将字符串日期更改为该时区。 有人指导我。

提前感谢。

2 个答案:

答案 0 :(得分:2)

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

如果您知道日期字符串的时区,请在格式化程序中设置它。我假设您需要在GMT时区中使用相同的日期格式。

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

答案 1 :(得分:2)

您需要使用TimeZone的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

相关问题