Search code examples
javaandroidcalendarandroid-calendarandroid-date

How to convert a String to a Calendar object?


To store a Calendar object in SQLite database, i found that the easiest way is to convert the Calendar object to a string and store it in the database as text.

Now, the problem lies in extracting the stored date from the string.

How do I parse the string containing the Calendar object and set it to a Calendar value?

My code is:

    String CREATE_DOCTORS_TABLE = "CREATE TABLE " + TABLE_DOCTORS + "("
            + KEY_ID_DOC + " INTEGER PRIMARY KEY," + KEY_DOCTOR_NAME + " TEXT,"             
            + KEY_CLINIC_ADDRESS + " TEXT," + KEY_LAST_CHECKUP + " TEXT" + ");";
    db.execSQL(CREATE_DOCTORS_TABLE);       

where KEY_LAST_CHECKUP contains a value like this:

java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=4,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=198,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=19,SECOND=47,MILLISECOND=823,ZONE_OFFSET=19800000,DST_OFFSET=0]

and i've stored it in a database this way:

values.put(KEY_LAST_CHECKUP, (doctor.getLastCheckUpDate().toString())); // last check up date

Now, how do i retrieve the DAY, MONTH and YEAR from the stored string?

I read about how to convert a date string to a calendar object here: How to convert a date String to a Date or Calendar object?

but my string is not just a date string. It contains a lot of other details too.

What is the best way forward?


Solution

  • Change your data model to use a Date. This is the usual type to be stored in the database.

    You can set the Date to a Calendar by using

    Calendar c = Calendar.getInstance();
    c.setTime(date);
    

    To retrieve the Date from a Calendar you can use

    date = c.getTime();
    

    Using a String to store a Date in a database needs formatting and parsing of the Strings and also no comparision iside the database can be done.