Home > Software engineering >  How to get users click in calendar view to be stored as dd/mm/yyyy in SQLite
How to get users click in calendar view to be stored as dd/mm/yyyy in SQLite

Time:02-03

In my SQLite database I have my dates stored in this format 02/01/2023 but when I try to get the date from the calendarview it gives them to me as 2/1/2023 which causes me to have an error when trying to retrieve the data from the database that matches that date.

How do I format this into a String variable?

My attempt so far:

    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();

CodePudding user response:

There is a better way (than what you have posted as an answer) to get the required formatted string:

String output = String.format("d/d/%d", day, month, year);

where day, month and year are integers.

Using java.time API:

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);
    }
}

Output:

01/02/2023

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

CodePudding user response:

This is how i got it to work:

        String sYear = String.valueOf(Year);
        String sMonth = String.valueOf((Month   1));
        String sDay = String.valueOf(Day);

        if (sDay.length() == 1)
            sDay = "0"   sDay;

        if (sMonth.length() == 1)
            sMonth = "0"   sMonth;

        if (sDay.length() == 1)
            sDay = "0"   sDay;

            date =   sDay   "/"   sMonth   "/"   sYear;
  • Related