Nebue
Nebue

Reputation: 1

Why are diferences between get milliseconds from LocalDateTime and Date from Calendar?

I'm porting my code from Timestamp to LocalDateTime, when I made a tests to get a milliseconds from LocalDateTime I saw a difference result from get it using Calendar and Date.

This is my "test":

System.out.println(LocalDateTime.of(2016,5,19,14,8,0).toInstant(ZoneOffset.UTC).toEpochMilli());

System.out.println(Timestamp.valueOf(LocalDateTime.of(2016,5,19,14,8,0)).getTime());

Calendar c = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("UTC")));
c.set(2016,5,19,14,8,0);

System.out.println(c.getTime().getTime());

I don't understand why the difference between those.

Upvotes: 0

Views: 139

Answers (1)

kornisb
kornisb

Reputation: 260

The result of your test is:

1463666880000
1463659680000
1466345280067

Each value is in milliseconds.

  • The difference between the first two values is exactly two hours. It is because in the first line you set UTC timezone and in the second line you didn't set anything, so it is in local timezone (and indeed, I am currently in UTC+2).

  • The difference in the first and the third values - apart from the millisecond part - is exaclty one month. It is because LocalDateTime.of() method expects the month argument represented from 1-12, but Calendar.set() expects month argument represented from 0-11. So in the third line you actually set 06/19/2016.

Upvotes: 2

Related Questions