如何让用户在日历视图中单击以在 SQLite 中存储为 dd/mm/yyyy

Joh*_*son 3 java android date

在我的 SQLite 数据库中,我的日期以这种格式存储:02/01/2023,但是当我尝试从日历视图获取日期时,它给我的日期为 2/1/2023,这导致我在尝试检索时出错数据库中与该日期匹配的数据。

如何将其格式化为字符串变量?

到目前为止我的尝试:

    public void onSelectedDayChange(@NonNull CalendarView calendarview, int i, int i1,int i2) {
        exercise_name = new ArrayList<>();
        set_weight = new ArrayList<>();
        set_reps = new ArrayList<>();
        set_date= new ArrayList<>();
    //formatting to dd/mm/yyyy
            System.out.println("both are over 10");
            date =    i2 + "/" + (i1+1) + "/" + i;

        //month needs plus 1 because it starts at 0
        tviewdate.setText(date);
        storeDataDateinArrays();
Run Code Online (Sandbox Code Playgroud)

Arv*_*ash 6

有一种更好的方法(比您作为答案发布的方法)来获取所需的格式化字符串:

String output = String.format("%02d/%02d/%d", day, month, year);
Run Code Online (Sandbox Code Playgroud)

其中daymonthyear是整数。

使用java.timeAPI​​:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");

        // Sample units
        int year = 2023, month = 2, day = 1;
        LocalDate date = LocalDate.of(year, month, day);
        String output = date.format(formatter);
        System.out.println(output);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出

01/02/2023
Run Code Online (Sandbox Code Playgroud)

ONLINE DEMO

从Trail: Date Time中了解有关现代日期时间 API 的更多信息。

  • 好答案。我怀疑 OP 的日期选择器使用基于 0 的月份数字(0 = 一月到 11 = 十二月),因此他们可能需要一个简单的转换。 (3认同)