将时间转换为美国不同时区

Aka*_*ash 1 java liferay jakarta-ee

我有一个要求,我从数据库中获取日期和时间。对于美国,有多个时区。所以我想将来自 DB 的时间转换为当前时区。

即我想要类似的东西,在 DB 时间存储为 GMT 格式,但想将该时间转换为 PST 用户的 PST、MST 用户的 MST、CST 用户的 CST 和 EST 用户的 EST。

编辑:: 不知何故,我能够获取不同时区的时间。

public static void main(String[] args) {
        Calendar localTime = Calendar.getInstance();
        localTime.setTime(new Date());
        System.out.println("PST::"+getTimeByTimezone("PST",localTime));
        System.out.println("MST::"+getTimeByTimezone("MST",localTime));
        System.out.println("CST::"+getTimeByTimezone("CST",localTime));
        System.out.println("EST::"+getTimeByTimezone("EST",localTime));
    }

    public static String getTimeByTimezone(String timeZone,Calendar localTime){     

        Calendar indiaTime = new GregorianCalendar(TimeZone.getTimeZone(timeZone));
        indiaTime.setTimeInMillis(localTime.getTimeInMillis());
        int hour = indiaTime.get(Calendar.HOUR);
        int minute = indiaTime.get(Calendar.MINUTE);
        int second = indiaTime.get(Calendar.SECOND);
        int year = indiaTime.get(Calendar.YEAR);
        //System.out.printf("India time: %02d:%02d:%02d %02d\n", hour, minute, second, year);
        return hour+":"+minute; 

    }
Run Code Online (Sandbox Code Playgroud)

但我想转换已经在页面上发布的时间。

JDC*_*JDC 5

您可以ZonedDateTimeJava 8 中使用:

public String getZonedDateString(Date date, ZoneId targetZoneId) {
    ZoneId zoneId = ZoneOffset.UTC; // This should be the zone of your database
    ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(date.toInstant(), zoneId);
    ZonedDateTime newZonedDateTime = zonedDateTime.withZoneSameInstant(targetZoneId);
    return DateTimeFormatter.ofPattern("MMM d yyy hh:mm") .format(newZonedDateTime);
}
Run Code Online (Sandbox Code Playgroud)

用法:

Date date = new Date();
ZoneOffset newZoneId = ZoneOffset.of(ZoneId.SHORT_IDS.get("MST"));
String dateString = getZonedDateString(date, newZoneId);
Run Code Online (Sandbox Code Playgroud)

在这里查看如何使用ZoneOffset


Java 8 之前:

public String getZonedDateString(Date date, TimeZone targetZone) {
    SimpleDateFormat format = new SimpleDateFormat("MMM d yyy hh:mm");
    format.setTimeZone(targetZone);
    return format.format(date);
}
Run Code Online (Sandbox Code Playgroud)

用法:

TimeZone targetZone = TimeZone.getTimeZone("MST");
String dateString = getZonedDateString(date, targetZone);
Run Code Online (Sandbox Code Playgroud)

在此处查看如何使用TimeZone