将时区转换回本地

时间:2014-04-07 12:13:15

标签: java groovy

我无法将Date对象转换回本地时区。我已经google了很多,无法找到解决方案。

我的方案是:我发送一个请求(在本地时区04/01 / 2014T00:00:00 + 0530中使用完整日期字符串)到位于其他时区的Web服务器。服务器适当地将其转换为UTC并进行一些操作并发回CSV文件。我在CSV中有一个日期列,它始终是GMT。

String input = "04/01/2014T00:00:00+0530";
DateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ssZ");
DateFormat csvFileDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm z");

Date inputDate = inputDateFormat.parse(input); // Mon Mar 31 18:30:00 GMT 2014
// inputDateFormat.getTimeZone(); // is always GMT

// After some processing I create CSV file
// within a loop
Date csvDate = // got Date from some operation, for simplicity I removed the code.
csvFileDateFormat.format(csvDate); // **HERE IS THE ISSUE**
// end of loop

我想正确设置csvFileDateFormat的时区。下面的代码工作,但我不想硬编码“GMT + 05:30”。而是只需要从输入字符串中提取时区。

csvFileDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+05:30")); // I dont want to hard code

非常感谢任何帮助。 PS:我没有选择使用任何其他库,如joda等......

此致 ArunDhaJ

2 个答案:

答案 0 :(得分:1)

也许这个功能可以帮到你:

private static TimeZone getTimeZoneFromString(String inputDateStr)
{
    // TimeZone inputTimeZone = null;
    // null or default
    TimeZone inputTimeZone = TimeZone.getDefault();
    try
    {
        DateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ssZ");
        Date inputDate = inputDateFormat.parse(inputDateStr);
        Date inputDate2 = inputDateFormat.parse(inputDateStr.substring(0, 19) + "+0000");
        int offset = (int) (inputDate2.getTime() - inputDate.getTime());
        for (String tzId : TimeZone.getAvailableIDs())
        {
            TimeZone tz = TimeZone.getTimeZone(tzId);
            if (tz.getOffset(inputDate.getTime()) == offset)
            { // take the first matching one, display name doesn't matter
                inputTimeZone = tz;
                break;
            }
        }
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }
    return inputTimeZone;
}

答案 1 :(得分:0)

您可以使用Locale.getDefault()返回正在运行的系统的默认时区。如果你不想返回它,那么硬编码应该是安全的。