Home > database >  How can I store two digit month in Firebase using Java?
How can I store two digit month in Firebase using Java?

Time:04-29

I've now tried a couple of different methods to get the format I want in my Firebase Database:

I use the java.util.Calendar import in Android Studio.

Method 1:

if (endMonth <= 9) {
    endYear = endYear * 10;
    endDate = Integer.toString(endYear)   Integer.toString(endMonth)   Integer.toString(endDay);
}

Method 2:

if (endMonth <= 9) {
    endDate = Integer.toString(endYear * 10)   Integer.toString(endMonth)   Integer.toString(endDay);
}

Method 3:

if (endMonth <= 9) {
    endDate = Integer.toString(endYear)   "0"   Integer.toString(endMonth)   Integer.toString(endDay);
}

I have also tried to store methods 1 and 2 as integers. However, they all end up in the Firebase Database as "2022328" or equivalent, whereas I want it to store as "20220328".

CodePudding user response:

I recommend using SimpleDateFormat for that.

SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String stringDate = formatter.format(date);            

Also see:

CodePudding user response:

You can format your date using SimpleDateFormatter:

Using Java:

Date date = Calendar.getInstance().getTime() // Today's date
String formattedDate = SimpleDateFormat("yyyyMMdd",Locale.getDefault()).format(date);

Using Kotlin:

val date = Calendar.getInstance().time // Today's date
val formattedDate = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(date);
  • Related