将时区更改为伦敦时的日期问题



我有下面的代码:

package com.company.customer;
import java.util.*;
import java.text.*;
import java.io.*;
public class DateSample {
    private TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
    private SimpleDateFormat sdfDate = new SimpleDateFormat();
    private Date inputDate;
    private String dateInString = "2015-07-15";
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    public void datePrint() {
        sdfDate.setTimeZone(GMT_TIMEZONE);
        sdfDate.applyPattern("EE-ddMMM");
        try {
            inputDate = formatter.parse(dateInString);
        } catch (Exception e) {
            System.out.println("populateTabDates: ParseException");
        }
        String formatResults = sdfDate.format(inputDate);
        // Modify the return to cut down the weekday: Fri-20Aug => Fr-20Aug
        formatResults = formatResults.substring(0, 2) + formatResults.substring(3);
        System.out.println(formatResults);
    }
}

当我将PC设置为伦敦时区并将PC时间更改为上午8点或9点时,问题出现了。然后,formatResults变量显示14而不是7月15;任何想法吗?

您还没有为formatter设置时区,所以这是系统默认的时区。

所以,您正在使用系统默认时区解析"2015-07-15"。如果是伦敦,则解析日期为2015-07-15T00:00:00+01,即2015-07-14T23:00:00Z。当你使用UTC时区和日期部分格式化时,你得到的是7月14日。

基本上将两个格式化器放入同一时区,或者您应该期望解析/格式化对"移动"该值。(如果您也在解析和格式化一天中的时间,这将更容易看到。)

我还建议使用UTC作为UTC时区的名称,而不是GMT;后者可能会让一些人误认为是英国时区,它在GMT和BST之间交替。

最新更新