在Java中将日期从UTC转换为EST?

Nik*_*ddy 3 java

我正在尝试将UTC的长时间戳转换为东部标准时间并完全丢失.任何提示都会很棒!

时间格式应为:11/4/03 8:14 PM在此先感谢!

TimeZone utcTZ= TimeZone.getTimeZone("UTC");
Calendar utcCal= Calendar.getInstance(utcTZ);
utcCal.setTimeInMillis(utcAsLongValue);



import java.text.SimpleDateFormat;
import java.util.Date;

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz");
sdf.setTimeZone(utcTZ);
Date utcDate= utcCal.getTime();
sdf.formatDate(utcDate);
Run Code Online (Sandbox Code Playgroud)

Ale*_*exR 6

昨天偶尔我写了以下方法,可以帮助你:

private Date shiftTimeZone(Date date, TimeZone sourceTimeZone, TimeZone targetTimeZone) {
    Calendar sourceCalendar = Calendar.getInstance();
    sourceCalendar.setTime(date);
    sourceCalendar.setTimeZone(sourceTimeZone);

    Calendar targetCalendar = Calendar.getInstance();
    for (int field : new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND}) {
        targetCalendar.set(field, sourceCalendar.get(field));
    }
    targetCalendar.setTimeZone(targetTimeZone);

    return targetCalendar.getTime();
}
Run Code Online (Sandbox Code Playgroud)

现在你只需格式化日期.为此使用SimpleDateFormat.这是一个例子:

DateFormat format = new SimpleDateFormat("dd/MM/yy hh:mm a");
format.format(date);
Run Code Online (Sandbox Code Playgroud)


sud*_*ode 6

您不应该考虑将日期转换为不同的时区.Java中的日期是,而且应该始终是UTC.

相反,您可以在要格式化日期时设置特定时区.这是一个例子:

public static void main(String[] args) throws Exception {

    String tzid = "EST";
    TimeZone tz = TimeZone.getTimeZone(tzid);

    long utc = System.currentTimeMillis();  // supply your timestamp here
    Date d = new Date(utc);

    // timezone symbol (z) included in the format pattern for debug
    DateFormat format = new SimpleDateFormat("yy/M/dd hh:mm a z");

    // format date in default timezone
    System.err.println(format.format(d));

    // format date in target timezone
    format.setTimeZone(tz);
    System.err.println(format.format(d));

}
Run Code Online (Sandbox Code Playgroud)

我的输出(我的默认时区是GMT):

11/12/19 10:06 AM GMT
11/12/19 05:06 AM EST
Run Code Online (Sandbox Code Playgroud)

或者,您可以在日历上设置时区,然后访问所需的日历字段.例如:

    Calendar c = Calendar.getInstance(TimeZone.getTimeZone("EST"));
    c.setTimeInMillis(utc);
    System.err.printf("%d/%d/%d %d:%d %s\n", c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR), c.get(Calendar.MINUTE), (c.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM"));
Run Code Online (Sandbox Code Playgroud)

(这不会为您提供您所要求的确切模式.)