Linux 服务器显示 UTC 而不是 EST,本地显示 EST

Linux server showing UTC instead of EST, local showing EST

我无法弄清楚为什么下面代码的时区一直显示 UTC 而不是 EST。在我的本地计算机上它显示 EST,即使我在 MST 时间但在实际服务器上它一直显示 UTC。有什么线索吗?

Mon Nov 9 2015 1:58:49 PM UTC


@JsonIgnore
    public String getDateCreatedFormatted() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getDateCreated());
        calendar.setTimeZone(TimeZone.getTimeZone("EST"));

        SimpleDateFormat format = new SimpleDateFormat("EEE MMM d yyyy h:mm:ss a z");      

        return format.format(calendar.getTime());
    }

您已将 日历 设置为 EST,但尚未在 SimpleDateFormat 上设置时区,这是用于格式化的。只需使用:

format.setTimeZone(TimeZone.getTimeZone("America/New_York"));

在格式化 Date 之前。从外观上看,您也根本不需要 Calendar

@JsonIgnore
public String getDateCreatedFormatted() {
    SimpleDateFormat format = new SimpleDateFormat("EEE MMM d yyyy h:mm:ss a z", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    return format.format(getDateCreated());
}

此外,我强烈 建议您使用上面的完整时区 ID,而不是像 "EST" 这样含糊不清的缩写。 (那里有两个问题 - 首先,EST 在不同的位置可能意味着不同的东西;其次,美国 EST 应该始终表示东部 标准 时间,而我假设你想使用东部时间进行格式化, 标准或夏令时取决于夏令时是否有效。)

java.time

java.util 日期时间 API 及其格式 API、SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*.

解决方案使用 java.time,现代日期时间 API:

@JsonIgnore
public String getDateCreatedFormatted() {
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/New_York"));
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM d uuuu h:mm:ss a z", Locale.ENGLISH);
    return dtf.format(now);
}

ONLINE DEMO

注: Never use SimpleDateFormat or DateTimeFormatter without a Locale.

Trail: Date Time.

了解有关现代日期时间 API 的更多信息

* 无论出于何种原因,如果您必须坚持使用 Java 6 或 Java 7,则可以使用 ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and