2

I have a variable date which is a string that needs to be in this format "yyyy-mm-dd" and i get the data from a variable of type CALENDAR so when the month or the day is less than 10, it only returns the digit "d" or "m". This is the code that i'm doing right now, it's not that good. Is there a better way to do this?

val date: String
if(cal.get(Calendar.MONTH)<9) {
           date = cal.get(Calendar.YEAR).toString() + "-0" +
(cal.get(Calendar.MONTH) + 1).toString() + "-" + cal.get(Calendar.DAY_OF_MONTH).toString()
                        }  
else {date = cal.get(Calendar.YEAR).toString() + "-"
 + (cal.get(Calendar.MONTH) + 1).toString() + "-" + cal.get(Calendar.DAY_OF_MONTH).toString()}

Thank you

mightyWOZ
  • 7,946
  • 3
  • 29
  • 46

2 Answers2

3

java.time through desugaring

Consider using java.time, the modern Java date and time API, for your date formatting work. In Java, it’s what I can write:

    LocalDate someDate = LocalDate.of(2021, Month.FEBRUARY, 6);
    String dateString = someDate.toString();
    System.out.println(dateString);

Output:

2021-02-06

The format that you are putting together, it agrees with the ISO 8601 standard (link at the bottom), and you can get it from the toString method of LocalDate. Could it be easier?

What is the difference between the variable type LocalDate and Calendar?

There are many differences between the old Calendar and the modern LocalDate class. It’s almost harder for me to think of any similarities. The following list is not exhaustive, but some important differences are:

  • The Calendar class is trying to be everything for every date and time purpose, which makes the design huge and complex. A LocalDate is for a date in the ISO or (proleptic) Gregorian calendar only, so is simple and straightforward.
  • A Calendar represents a date and time of day in a time zone with week numbering scheme and more. As i said, a LocalDate represents a date, so it’s without time of day and without time zone. If you need any of that, there are other good classes of java.time for you to use.
  • A Calendaris mutable and not thread safe. A LocalDate is immutable and therefore thread-safe by design.
  • Calendar is an abstract superclass of classes for different calendar systems: Julian/Gregorian and Thai Buddhist, for example. So when what you know is that you’ve got a Calendar object, you don’t know which calendar system it belongs to. LocalDate is a final class, it can’t have any subclasses, and it always belongs to the proleptic Gregorian calendar (java.time also provides classes for dates in other calendar systems).
  • Calendar has an old-fashioned design with very general get and set methods. You will often see people calling set 3 or 7 times in a row to make some modification to the object. LocalDate is designed for a fluent API where you may do things like myLocalDate.with(Month.APRIL).withDayOfMonth(30) in one statement that most find straightforward to read once they have got accustomed to the style.
  • Output from Calendar.toString is virtually unreadable. To format its value you were originally supposed to extract a Date from it and format it using a SimpleDateFormat (a still more troublesome class), and to get the values of the Calendar through you would need to remember to set the TimeZone and possibly other attributes of the SimpleDateFormat according to the Calendar. LocalDate.toString gives output in ISO 8601 format as we saw.

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
2

Manual date and time formatting is not a very good idea, Java SDK includes many classes to make the date and time formatting easy, SimpleDateFormat is one of them, go ahead and read the documentation. Following is the code snippet on how to use it

val formatter = SimpleDateFormat("yyyy-MM-dd")
val formattedDate = formatter.format(Calendar.getInstance().time)

"yyyy-MM-dd" is the format pattern. with every character having following meaning

  1. y - year (yyyy because we need 4 characters for year as in 2021 )

  2. M(Capital M) - month in year (MM because we need at least two characters for month (so if month is less than 10 its written as 01,04 etc))

  3. dd - day in month (we write dd because we need at least two characters for day same as month)

  4. -(Hyphen) - its a delimiter

This is just basic stuff, read the documentation for complete understanding.

mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
  • `SimpleDateFormat` is long outdated and notoriously troublesome. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android look into [desugaring](https://developer.android.com/studio/write/java8-support-table). – Ole V.V. Jan 30 '21 at 09:48