在Java中将HHMM字符串转换为GMT格式

时间:2011-07-14 15:26:10

标签: java date

我需要将形式为HHMM的字符串(在EST或EDT中 - 今天)转换为格式为YYYYMMDD-HH:MM:SS的GMT时间戳。因此,如果我得到1512,我想在GMT时间和格式中表达3:12EDT:20110714-20:12:00。我怎么能这样做?

我尝试过以下代码,但根本不进行转换。

    int hour = Integer.parseInt(HHMM.substring(0, 2));
    int min  = Integer.parseInt(HHMM.substring(2, 4));

    Date day = new Date();
    day.setHours(hour);
    day.setMinutes(min);
    day.setSeconds(00); 
    DateFormat gmtFormat = new SimpleDateFormat();
    gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    gmtFormat.format(day);

    return day.getYear() + "" + day.getMonth() + "" + 
           day.getDate() + "-" + day.getHours() + ":" + 
           day.getMinutes() + ":" + day.getSeconds();

4 个答案:

答案 0 :(得分:1)

Joda

中,它更短更清晰(IMO)
public static String printIsoTime(String hhmm)    {
    DateTimeFormatter fmt = DateTimeFormat.forPattern("HHmm");

    // construct datetime from local midnight + parsed hhmm
    DateTime localDateTime = new LocalDate().toDateTime(
        fmt.parseDateTime(hhmm).toLocalTime());

    // convert to UTC and print in ISO format
    return ISODateTimeFormat.dateHourMinuteSecond()
        .print(localDateTime.withZone(DateTimeZone.UTC));
}

答案 1 :(得分:0)

怎么样,

    //obtain a formatted string with the year day month information for today
    Date today = new Date();
    SimpleDateFormat todaySdf = new SimpleDateFormat("yyyyMMdd-");
    String todaySdfString = todaySdf.format(today);

    //now concatenate today's info from above with the time info and then parse the whole thing
    SimpleDateFormat edtFormat = new SimpleDateFormat("yyyyMMdd-HH:mmz");
    Date dt = edtFormat.parse(todaySdfString+"15:12EDT");

    //now GMT
    SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyyMMdd-HH:mm:ss");
    gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String fmtDt = gmtFormat.format(dt);
    System.out.println("fmtDt = " + fmtDt);

答案 2 :(得分:0)

你应该真正使用日历,但是你现在设置它的方式应该可行:

Date day = new Date();
day.setHours(3);
day.setMinutes(12);
day.setSeconds(00);

SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyyMMdd-hh:mm:ss");
gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT") );

Date fmtDay = gmtFormat.format(day);
System.out.println("fmtDay: " + fmtDay);

答案 3 :(得分:0)

感谢您的回复,我结合了几个答案,最后得到了以下代码,这些代码正确转换为GMT并为我提供了我需要的格式化字符串。

private static String convertHHMMtoGMT(String HHMM)
{       
    Calendar day = Calendar.getInstance();
    day.set(Calendar.HOUR_OF_DAY, hour);
    day.set(Calendar.MINUTE, min);
    day.set(Calendar.SECOND, 00);
    day.set(Calendar.MILLISECOND, 00);    

    SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyyMMdd-HH:mm:ss");
    gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

    return gmtFormat.format(day.getTime());
}