我有一个要求,我要从数据库中获取日期和时间。美国有多个时区。所以我想将来自数据库的时间转换为当前时区。
即我想要类似的东西,在数据库中时间存储为 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;
}
但是我想转换已经发布在页面上的时间。
最佳答案
您可以在 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
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
关于java - 将时间转换为美国不同时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41139607/