I recommend that you use java.time, the modern Java date and time API, for your date work. If I have understood that Firebase doesn’t provide a date
data type, then I think that for storing you will want:
String currentDateandTime = LocalDate.now(ZoneId.systemDefault()).toString();
System.out.println(currentDateandTime);
Output when running just now in my time zone:
2021-04-17
The result is independent of locale. On retrieval the one-arg LocalDate.parse(CharSequence)
will parse the same string back into a LocalDate
.
Edit: The format you want, 2021-04-17, is an international standard known as ISO 8601, and I consider it wise of you to use it in your program too. I am exploiting the fact that LocalDate
and the other classes of java.time produce ISO 8601 from their toString
methods and parse the same format back in their one-arg parse
methods. So when dealing with ISO 8601 (as a rule) we don’t need to specify a format nor a formatter neither for formatting nor for parsing. Had you wanted a different format, you would have used a DateTimeFormatter
for specifying it.
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 either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links