java 毫秒转时间字符串,从毫秒转换为日期字符串

I try to convert from Milliseconds to string of date. However, the result is not correct as my expected.

The input is milliseconds (Ex: 1508206600485)

My time zone is UTC +10:00

------Expected-------------------------------------------- Actual------

01:32 (PM) 17/10/2017--------------------------------02:32 (PM) 17/10/2017

Here is the method of that

public static String getDate(long milliSeconds) {

SimpleDateFormat formatter = new SimpleDateFormat("hh:mm dd/MM/yyyy");

String dateString = formatter.format(new Date(milliSeconds));

return dateString;

}

解决方案

Good you found a solution, I just like to add an approach with Java 8 new java.time API. The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and it's strongly recommended to switch to the new API if possible.

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP (more on how to use it here).

The code below works for both.

The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.

To convert the millis value to a specific timezone, you can use the Instant class, then use a ZoneId to convert to a timezone, creating a ZonedDateTime.

Then you use a DateTimeFormatter to format it:

// convert millis value to a timezone

Instant instant = Instant.ofEpochMilli(1508206600485L);

ZonedDateTime z = instant.atZone(ZoneId.of("Australia/Sydney"));

// format it

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm dd/MM/yyyy");

System.out.println(fmt.format(z)); // 01:16 17/10/2017

The output is:

01:16 17/10/2017

Note that I used hh for the hours. According to javadoc, this lettern represents the clock-hour-of-am-pm field (values from 1 to 12), so without the AM/PM indicator, it can be ambiguous. Maybe you want to add AM/PM field (adding the letter a to the format pattern), or change the hours to HH (hour-of-day, with values from 0 to 23).

Also note that the actual value of the ZonedDateTime is 2017-10-17T13:16:40.485+11:00 (01:16 PM), because in October 17th 2017, Sydney is in Daylight Saving Time, so the actual offset is +11:00.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值