如何将getTime()转换为’YYYY-MM-DD HH24:MI:SS’
我在我的应用程序中有以下代码
System.out.println(rec.getDateTrami().getTime());
我需要转换以下格式(我想它们是秒)
43782000 29382000 29382000
格式YYYY-MM-DD HH24:MI:SS
,有人可以帮我吗?
您可以使用SimpleDateFormat
例:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = new Date(); date.setTime(rec.getDateTrami().getTime()); System.out.println(format.format(date));
文档: SimpleDateFormat , DateFormat
使用java.time
如果您可以更改getDateTrami()
以从java.time
返回OffsetDateTime
或ZonedDateTime
, java.time
。 java.time
是现代Java的日期和时间API。 它也被称为JSR-310。 无论返回两种提到的类型中的哪一种,代码都是相同的:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"); System.out.println(rec.getDateTrami().format(formatter));
这会打印日期和时间
2017-12-14 16:52:20
java.time
通常比过时的Date
类及其朋友更好。
如果无法更改返回类型
我假设getDateTrami()
返回一个java.util.Date
。 由于Date
类过时,所以要做的第一件事就是将其转换为java.time.Instant
。 从那里你执行进一步的操作:
Date oldfashionedDateObject = rec.getDateTrami(); ZonedDateTime dateTime = oldfashionedDateObject.toInstant() .atZone(ZoneId.of("Atlantic/Cape_Verde")); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"); System.out.println(dateTime.format(formatter));
当然,结果与上述类似。 我故意明确说明我想在哪个时区解释时间点。 如果它不是Atlantic / Cape_Verde,请替换你自己。
格式化自纪元以来的秒数
int seconds = 29_382_000; ZonedDateTime dateTime = Instant.ofEpochSecond(seconds) .atZone(ZoneId.of("Atlantic/Cape_Verde")); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"); System.out.println(dateTime.format(formatter));
这个片段打印出来
1970-12-06 23:40:00
1970年12月的日期。如果这是不正确的,那是因为29 382 000并不表示自1970年1月1日UTC午夜时期以来的秒数,也称为Unix时代。 这是迄今为止测量秒数的最常见时间。 如果您的秒数是从某个其他固定时间点测量的,我无法猜测哪一个,并且您还有一份工作要做。 再次确定要指定的时区。
您可以使用SimpledateFormat。
new SimpleDateFormat("YYYY-MM-DD HH24:MI:SS").format(date)