Kev*_*rds 3 java datetime date simpledateformat
我正在从纪元时间(UTC时间)转换为如下所示的格式。现在,我尝试了不同的答案SO转换UTCDate从UTC本地时间。但是我没有当地时间。
任何帮助,将不胜感激。
String epochTime = "1436831775043";
Date UTCDate = new Date(Long.parseLong(epochTime));
Date localDate; // How to get this?
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
String result = simpleDateFormat.format(UTCDate);
Run Code Online (Sandbox Code Playgroud)
另外,转换必须在没有任何外部库帮助的情况下完成。
String epochTime = "1436831775043";
Instant utcInstant = new Date(Long.parseLong(epochTime)).toInstant();
ZonedDateTime there = ZonedDateTime.ofInstant(utcInstant, ZoneId.of("UTC"));
System.out.println(utcInstant);
LocalDateTime here = there.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(here);
Run Code Online (Sandbox Code Playgroud)
哪个输出:
2015-07-13T23:56:15.043Z
2015-07-14T09:56:15.043
Run Code Online (Sandbox Code Playgroud)
我想你是在追尾巴。 Date只是一个从纪元(1970年1月1日,格林尼治标准时间00:00:00)以来的毫秒数的容器。它在内部不带有时区(AFAIK)的表示。
例如...
String epochTime = "1436831775043";
Date UTCDate = new Date(Long.parseLong(epochTime));
// Prints the "representation" of the Date
System.out.println(UTCDate);
// Local date/time format...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm:ss a");
try {
System.out.println("local format: " + simpleDateFormat.format(UTCDate));
System.out.println("local Date: " + simpleDateFormat.parse(simpleDateFormat.format(UTCDate)));
} catch (ParseException ex) {
Logger.getLogger(JavaApplication203.class.getName()).log(Level.SEVERE, null, ex);
}
// UTC date/time format
try {
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("utc format: " + simpleDateFormat.format(UTCDate));
System.out.println("utc date: " + simpleDateFormat.parse(simpleDateFormat.format(UTCDate)));
} catch (ParseException ex) {
Logger.getLogger(JavaApplication203.class.getName()).log(Level.SEVERE, null, ex);
}
Run Code Online (Sandbox Code Playgroud)
哪个输出...
Tue Jul 14 09:56:15 EST 2015
local format: 14/07/2015 9:56:15 AM
local Date: Tue Jul 14 09:56:15 EST 2015
utc format: 13/07/2015 11:56:15 PM
utc date: Tue Jul 14 09:56:15 EST 2015
Run Code Online (Sandbox Code Playgroud)
如果您看一下,即使格式和格式正确local Date,utc date它们也是同一回事。local formatutc format
因此,Date使用Java 8的Time API或JodaTime来管理时区信息,或者只是将其格式化Date为所需的时区,而不是去尝试试图“代表”您想要的值的故事吧。
此外,如果我们做类似的事情...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm:ss a");
Date localDate = simpleDateFormat.parse(simpleDateFormat.format(UTCDate));
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcDate = simpleDateFormat.parse(simpleDateFormat.format(UTCDate));
System.out.println(localDate.getTime());
System.out.println(utcDate.getTime());
System.out.println(localDate.equals(utcDate));
Run Code Online (Sandbox Code Playgroud)
它将打印...
1436831775000
1436831775000
true
Run Code Online (Sandbox Code Playgroud)