我从gpslocation服务中得到了一个时间,它采用了1352437114052格式。有人能告诉我如何在Java、Matlab或Excel中将其转换为本地时间吗?
将您的自纪元以来的毫秒数创建一个新的Date
。然后使用DateFormat
在您所需的时区格式化它。
Date date = new Date(1352437114052L);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(format.format(date));
这是一个时代时间,它代表的是2012年11月9日星期五04:58:34 GMT。该数字值是一个绝对时间点,与时区无关。
如果您想在不同的时区看到该时间点,请使用GregorianCalendar
:
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"));
c.setTimeInMillis(1352437114052L);
c.get(Calendar.HOUR_OF_DAY); //20:58 the day before
TimeZone
。否则,您将得到默认时区。 - David R TribbleDateTime converted = c.getTime();
获取转换后的日期时间。 - Vincent使用JVM的时区设置(通常与计算机的时区相同)的现代Java解决方案:
long time = 1_352_437_114_052L;
ZonedDateTime dateTime = Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault());
System.out.println(dateTime);
2012-11-09T05:58:34.052+01:00[Europe/Copenhagen]
指定时区:
ZonedDateTime dateTime = Instant.ofEpochMilli(time).atZone(ZoneId.of("Asia/Almaty"));
2012-11-09T10:58:34.052+06:00[Asia/Almaty]
回答这里的tinker评论:是的。我正在使用现代的Java日期和时间APIjava.time
,它在旧版和新版的Android设备上都能很好地工作。只需要至少Java 6。
org.threeten.bp
的子包导入日期和时间类。java.time
。java.time
。java.time
回溯到Java 6和7(ThreeTen for JSR-310)。long timeStamp = System.currentTimeMillis();
System.out.println(timeStamp+"");
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timeStamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a z");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString);
输出:
timestamp : 1528860439258
dateformat from sdf : 2018-06-12 08:27:19 PM PDT
SimpleDateFormat
类。至少不要将其作为首选项。而且不要毫无保留地使用它。今天,我们在java.time
,现代Java日期和时间API及其DateTimeFormatter
中有更好的选择。 - Ole V.V.@Steve Kuo几乎直接回答了这个问题。这里有一个更一般的解决方案,适用于机器的本地时间,包括夏令时,其中a
是从Windows目录条目中报告的BasicFileAttributes
类型,在public FileVisitResult visitFile(Path f, BasicFileAttributes a)
期间使用Files.walkFileTree
:
String modifyDate;
Date date = new Date(a.lastModifiedTime().to(TimeUnit.MILLISECONDS));
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(TimeZone.getDefault());
modifyDate = (format.format(date)).substring(0,10);
由于现在已经弃用了new Date(String string)(这是被接受的答案),我们可以使用DateTimeZone.getDefault()
来获取系统时区
public String getZonedDate(String dateStr) {
DateTime utcDateTime = new DateTime(dateStr).toDateTime(DateTimeZone.UTC);
return utcDateTime
.toDateTime(DateTimeZone.getDefault()).toString("yyyy-MM-dd'T'HH:mm:ss");
}