Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It's odd enough, but I didn't find any result about converting Joda(Time) DateTime to Unix DateTime (or timestamp, whichever is the correct name). How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
362 views
Welcome To Ask or Share your Answers For Others

1 Answer

Any object that inherits from BaseDateTime (including DateTime) has the method

public long getMillis()

According to the API it:

Gets the milliseconds of the datetime instant from the Java epoch of 1970-01-01T00:00:00Z.

So a working example to get the seconds would simply be:

new DateTime().getMillis() / 1000

For completeness, the definition of the Unix Timestamp according to Wikipedia:

Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds.

You can also improve it further by removing the magic number division using the TimeUnit API:

import java.util.concurrent.TimeUnit;

TimeUnit.MILLISECONDS.toSeconds(new DateTime().getMillis());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...