LocalDate and ThreeTenABP
String dateString = "2019-11-27";
LocalDate date = LocalDate.parse(dateString);
int epochDay = (int) date.toEpochDay();
System.out.println(epochDay);
This snippet outputs:
18227
The documentation explains:
The Epoch Day count is a simple incrementing count of days where day 0
is 1970-01-01 (ISO).
So my suggestion is that this number is fine for feeding into your BarEntry
constructor.
toEpochDay()
returns a long
. If your constructor doesn’t accept a long
, convert to int
. In the code above I did a simple cast. The risk is that we will get a very wrong result in case of int
overflow for dates in the far future or the far past. I prefer to do a range check to avoid that:
long epochDayLong = date.toEpochDay();
if (epochDayLong < Integer.MIN_VALUE || epochDayLong > Integer.MAX_VALUE) {
throw new IllegalStateException("Date " + date + " is out of range");
}
int epochDay = (int) epochDayLong;
The result is the same as before. This check is the same check that the Math.toIntExact
method I mentioned in a comment does (available from Android API level 24).
I had converted this value 18227 to normal date and it gives date
of this year 1970/01/01 and in JSON it's 2019-11-27 why? and
how should i correct it?
Let me guess, you effectively did new Date(18227)
. My suggestion is that you avoid the Date
class completely and stick to java.time, the modern Java date and time API. Why you got 1970 is: 18227 is a count of days since the epoch, and Date
counts milliseconds (since 00:00 UTC on the epoch day). So you got 00:00:18.227 UTC on that day. We already have a LocalDate
in the above code, so just use that.
System.out.println(date);
2019-11-27
Should you need to convert the opposite way, it’s easy when you know how:
LocalDate convertedBack = LocalDate.ofEpochDay(epochDay);
The result is a LocalDate
with the same value.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both 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 non-Android 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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…