java - 日期时区从字符串转换为日期到字符串 [英] java - Date Timezone Conversion From String to Date to String

查看:512
本文介绍了java - 日期时区从字符串转换为日期到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a routine which receives a date in the format yyyy, MMM dd, HH:mmin GMT time. I have to convert this String to a Date object and I do it with a SimpleDateFormat, but now I have to take that Date object and format it in GMT-5 using again a SimpleDateFormat, but the method is returning the same original String Date. Why? This is my routine:

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


推荐答案

p>

Solved by indicating the Timezone of the receiving date string:

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

这篇关于java - 日期时区从字符串转换为日期到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆