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

时间:2016-12-14 09:56:34

标签: java java-ee liferay

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

即我希望类似,在DB时间内存储为GMT格式,但希望将该时间转换为PST用户,MST用户,CST用户和CST用户和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; 

    }

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

2 个答案:

答案 0 :(得分:4)

您可以在 Java 8

中使用ZonedDateTime
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);
}

用法:

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

请在此处查看如何使用ZoneOffset

Pre 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);
}

用法:

TimeZone targetZone = TimeZone.getTimeZone("MST");
String dateString = getZonedDateString(date, targetZone);

请在此处查看如何使用TimeZone

答案 1 :(得分:0)

它对我来说非常好。 现在我可以将GMT转换为PST时区。

DateFormat gmtFormat = new SimpleDateFormat("HH:mm");
        gmtFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

        Date date = null;
        try {
            date = gmtFormat.parse("11:10");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        DateFormat pstFormat = new SimpleDateFormat("HH:mm");
        pstFormat.setTimeZone(TimeZone.getTimeZone("PST"));

        String timedd = pstFormat.format(date);
        System.out.println(pstFormat.format(date));