java - 日期时区从字符串到日期到字符串的转换

时间:2015-08-03 20:32:34

标签: java date datetime

我有一个例程,它在GMT时间内以yyyy, MMM dd, HH:mm格式接收日期。我必须将此String转换为Date对象,并使用SimpleDateFormat进行,但现在我必须使用Date对象并使用SimpleDateFormat再次格式化GMT-5,但方法返回相同的原始字符串日期。为什么?这是我的惯例:

public static TimeZone destinationTimeZone = TimeZone.getTimeZone("GMT-4");

public static Date parseDate(String date, String format) {
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return d;
}

public static String formatDate(Date date, String format) {
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
    formatter.setTimeZone(destinationTimeZone);
    return formatter.format(date);
}

@Test
public void testDateConversion() {
    String strDate = "2015, Aug 03, 23:50";
    Date date = DateFormatter.parseDate(strDate, "yyyy, MMM dd, HH:mm");

    String dateFormatted = DateFormatter.formatDate(date, "yyyy, MMM dd, HH:mm");
    assertEquals("2015, Aud 03, 19:50", dateFormatted); // Fails
}

错误讯息:

org.junit.ComparisonFailure: 
Expected :2015, Aug 03, 19:50
Actual   :2015, Aug 03, 23:50

2 个答案:

答案 0 :(得分:1)

通过指示接收日期字符串的时区来解决:

public static TimeZone originTimeZone = TimeZone.getTimeZone("GMT"); // +Added
public static TimeZone destinationTimeZone = TimeZone.getTimeZone("GMT-4");

public static Date parseDate(String date, String format) {
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
    formatter.setTimeZone(originTimeZone);// +Added
    Date d = null;
    try {
        d = formatter.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return d;
}

public static String formatDate(Date date, String format) {
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
    formatter.setTimeZone(destinationTimeZone);
    return formatter.format(date);
}

答案 1 :(得分:0)

尝试将传入的字符串更改为格式,如此

@Test
public void testDateConversion() {
    //also changed this from 23:50 to 19:50
    String strDate = "Aug 03, 2015, 19:50";
    Date date = parseDate(strDate, "MMM dd, yyyy, HH:mm");

    String dateFormatted = formatDate(date, "yyyy, MMM dd, HH:mm");
    assertEquals("2015, Aud 03, 19:50", dateFormatted); // Fails
} 

否则您的代码按预期格式化。问题是,您在预格式化中传递了日期字符串,因此您的结束不会改变您的开始。您的单元测试失败了,因为您正在传递"Aug 03, 2015, 23:50"并告诉Junit期待"Aug 03, 2015, 19:50";。当您将字符串传递给日期时,时间值根本不会改变