将即时时间转换为本地时间的 Java 程序
假设你需要将即时时间转换为带时区的本地时间
创建一个即时时间
Instant instant = new Date().toInstant();
现在,将即时时间转换为本地时间
LocalDateTime date = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneId.SHORT_IDS.get("IST")));
示例
import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; public class Demo { public static void main(String[] args) { Instant instant = new Date().toInstant(); LocalDateTime date = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneId.SHORT_IDS.get("IST"))); System.out.println("Date (IST) = " + date); date = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneId.SHORT_IDS.get("PST"))); System.out.println("Date (PST) = " + date); date = LocalDateTime.ofInstant(instant, ZoneId.of(ZoneId.SHORT_IDS.get("EST"))); System.out.println("Date (EST) = " + date); } }
输出
Date (IST) = 2019-04-18T13:32:26.923 Date (PST) = 2019-04-18T01:02:26.923 Date (EST) = 2019-04-18T03:02:26.923
广告