0

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".

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
DJ Feder
  • 3
  • 1

2 Answers2

0

I recommend using SimpleDateFormat for that.

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

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank You! Your link helped out alot!! Have a great weekend ^-^ – DJ Feder Apr 28 '22 at 23:29
  • Consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. Use [desugaring](https://developer.android.com/studio/write/java8-support-table) in order to use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It is so much nicer to work with. – Ole V.V. Apr 29 '22 at 04:12
0

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);
Izak
  • 909
  • 9
  • 24
  • Is it possible to make this work, when calculating the date the next day? I'm not sure how to do it when using the Date. – DJ Feder Apr 28 '22 at 23:21
  • @DJFeder It’s easy, but then you will need to switch to java.time as mentioned in my comment under the other answer. You may for instance define `LocalDate currentDay = LocalDate.now(ZoneId.systemDefault());` and then `LocalDate nextDay = currentDay.plusDays(1);`. The format you ask for is built in, so formatting goes like `String endDate = nextDay.format(DateTimeFormatter.BASIC_ISO_DATE);`. – Ole V.V. Apr 29 '22 at 06:11