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?
Asked
Active
Viewed 4.8k times
36

OneCricketeer
- 179,855
- 19
- 132
- 245

Incerteza
- 32,326
- 47
- 154
- 261
3 Answers
92
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());

Bruno Paulino
- 5,611
- 1
- 41
- 40

reto
- 9,995
- 5
- 53
- 52
-
Suggested improvement to get rid of the constant. ` TimeUnit.MILLISECONDS.toSeconds(new DateTime().getMillis())` – Synesso Jun 27 '19 at 06:04
5
Java 8 added a new API for working with dates and times. With Java 8 you can use
long unixTimestamp = Instant.now().getEpochSecond();

OneCricketeer
- 179,855
- 19
- 132
- 245

Navrattan Yadav
- 1,993
- 1
- 17
- 22
-
22
-
6Yes it is, he uses and links to joda's `DateTime` in the answer. – Stephen Carman Apr 19 '16 at 15:01
-
5
-
2How does this answer have upvotes? Literally not an answer to the question. – Andrew Koster Nov 19 '19 at 20:51
-
0
@Test
public void covertDateTimeToEpoch() {
DateTime dateTime = DateTime.parse("2020-07-09T04:30:45.781Z");
long epochMilli = dateTime.toDate().toInstant().toEpochMilli();
assertEquals(1594269045781L, epochMilli);
}

TechPassionate
- 1,547
- 1
- 11
- 18