将日期从UTC转换为CET

时间:2016-05-09 10:29:41

标签: java date

我想将UTC格式的日期转换为CET格式的日期。

问题是我需要相应地增加或减少小时数。

示例:

Date = "2015-07-31 01:14:05"

我想将其转换为德国日期(增加两小时):

2015-07-31 03:14:05" 

我的代码:

private static Long convertDateFromUtcToCet(String publicationDate) {
    //"2015-07-31 01:14:05"

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
    //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
    Date date = null;
    try {
        date = simpleDateFormat.parse(publicationDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.setTime(date);
    Date givenDate = calendar.getTime();
    System.out.println("Original UTC date is: " + givenDate.toString());

    TimeZone timeZone = TimeZone.getTimeZone("CET");
    calendar.setTimeZone(timeZone);
    Date currentDate = calendar.getTime();
    System.out.println("CET date is: " + currentDate.toString());

    long milliseconds = calendar.getTimeInMillis();

    return milliseconds;
}

打印:

Original UTC date is: Sat Jan 31 01:14:05 IST 2015
CET date is: Sat Jan 31 01:14:05 IST 2015

2 个答案:

答案 0 :(得分:2)

首先,你的模式字符串是错误的。它是yyyy-MM-dd,而不是yyyy-mm-dd

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

要使用给定时区进行解析,请将其设置为:

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

答案 1 :(得分:1)

尝试使用:

long ts = System.currentTimeMillis();
Date localTime = new Date(ts);
String format = "yyyy-mm-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);

// Convert Local Time to UTC (Works Fine)
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmtTime = new Date(sdf.format(localTime));
System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:"
        + gmtTime.toString() + "," + gmtTime.getTime());


// Convert UTC to Local Time
Date fromGmt = new Date(gmtTime.getTime() + TimeZone.getDefault().getOffset(localTime.getTime()));
System.out.println("UTC time:" + gmtTime.toString() + "," + gmtTime.getTime() + " --> Local:"
        + fromGmt.toString() + "-" + fromGmt.getTime());