如何使用 Java 在 Firebase 中存储两位数的月份?

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

我现在尝试了几种不同的方法来在我的 Firebase 数据库中获取我想要的格式:

我在 Android Studio 中使用 java.util.Calendar 导入。

方法一:

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

方法二:

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

方法三:

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

我也尝试过将方法 1 和 2 存储为整数。但是,它们最终都在 Firebase 数据库中作为“2022328”或等效项结束,而我希望它存储为“20220328”。

我建议为此使用 SimpleDateFormat

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

另见:

  • Calendar date to yyyy-MM-dd format in java

您可以使用 SimpleDateFormatter 格式化您的日期:

使用Java:

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

使用 Kotlin:

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