简体   繁体   中英

java convert long to formatted string (less than an hour)

251786 <-> 00:04:11,786

Date date = new Date(251786);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss,SSS");
String dateFormatted = formatter.format(date);

However, dateFormatted's value is 18:04:11,786

What happens to HH?

Your argument for the Date constructor (251786), indicates almost 252 seconds since epoch (or January 1, 1970, 00:00:00 GMT). Assuming your machine isn't running in GMT you're getting the local time offset - or January 1, 1970 00:04:11,786 GMT - and I'm guessing you're in GMT-6 (ie your timezone is 6 hours behind GMT, so you get 18 in the hours field - or 6 pm).

http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(long)

Date(long date) Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

I agree with @Elliott and in addition to that little bit more explanation is here :).

As you're in GMT-6 (6 hours behind GMT) standard the epoch will be taken as January 1, 1970, 18:00:00 rather than January 1, 1970, 00:00:00 GMT

And then what ever the argument( 251786 ) you pass to Date constructor will be added to the epoch . In you case It will be January 1, 1970, 18:00:00 000 + 251786 -> the result you see will be January 1, 1970, 18:04:11 786 .

You can understand it more by trying it out with pattern EEE, d MMM yyyy hh:mm:ss,SSS or even other patterns.

Date date = new Date(251786);
DateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss,SSS");
String dateFormatted = formatter.format(date);

Its absolutely 4 minutes and 11 seconds, that's what it is showing.

Your milliseconds argument need to be increased to get hours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM