0

calendar gets wrong unix time as I got.

long millis = 1568814839L;
System.out.println(millis); //1568814839
Calendar.getInstance(TimeZone.getTimeZone("Asia/Tashkent"));
calendar.setTimeInMillis(millis);
System.out.println(calendar.get(Calendar.MILLISECOND));//839

What should I do? Calendar.YEAR should be 2019 with that millis. However, calendar gives me 1970, why?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
sardorkun
  • 87
  • 2
  • 11

2 Answers2

1

The error is due to you confusing time in milliseconds and time in seconds. 1568814839L is the number of seconds since 1/1/1970, but you're treating it as milliseconds. This is quite easy to check:

long millis = 1568814839L;
System.out.println(millis); //1568814839
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tashkent"));
System.out.println(calendar.getTimeInMillis()); //1568820981321
calendar.setTimeInMillis(millis);
System.out.println(calendar.get(Calendar.YEAR));//839

This will produce:

1568814839
1568820981321
1970

As you can see, your number is 3 orders of magnitude off. Add three 0's to the end of your millis number:

long millis = 1568814839000L;
...
System.out.println(calendar.get(Calendar.YEAR));

Now you get:

1568814839000
1568821211006
2019
Aleks G
  • 56,435
  • 29
  • 168
  • 265
1

java.time

The modern code would use java.time, the modern Java date and time API.

Feed your count of whole seconds since 1970-01-01T00:00Z to the Instant class:

    ZonedDateTime zdt = Instant.ofEpochSecond(1_568_814_839L)
                               .atZone(ZoneId.of("Asia/Tashkent"));
    System.out.println(zdt);
    System.out.println("Year: " + zdt.getYear());
    System.out.println("Millisecond of second: "
                        + zdt.get(ChronoField.MILLI_OF_SECOND));

Output is:

2019-09-18T18:53:59+05:00[Asia/Tashkent]
Year: 2019
Millisecond of second: 0

As others have said, your number is seconds since the epoch, not milliseconds.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161