elbereth
elbereth

Reputation: 37

Saving a date of type string into a database as type Date

I need to save a couple of dates into a database in Java. These dates are first received as strings. How do I convert them and save them as Date in the database? I was planning to use a STR_TO_DATE function, but how would the syntax for the query look like in that case?

This is what I have so far:

public void addRow(Integer id, String infName, String infType,
    String domain, String language, String validType, Integer infoTypeId,
    String value, String effDate, String expDate, String processingTime)
    {
        String query="id+infName+language";
        if(query!=KEY)
        {
            try
            {
                                    // asking for a database
                SQLiteDatabase db=this.getWritableDatabase();
                ContentValues values=new ContentValues();

                values.put(PERSON_ID,id);
                values.put(INFO_NAME,infName);
                values.put(INFO_INPUT_TYPE,infType);
                values.put(INFO_DOMAIN, domain);
                values.put(INFO_LANGUAGE, language);
                values.put(INFO_REG_EX, validType);
                values.put(INFO_TYPE_ID,infoTypeId);
                values.put(INFO_VALUE, "NoValue");

// DATE-shouldnt be added as a string but as a DATE or TIMESTAMP
                values.put(INFO_EFFECTIVE_DATE, effDate);
// DATE-shouldnt be added as a string but as a DATE or TIMESTAMP
                values.put(INFO_EXPIRY_DATE, expDate);

                values.put(INFO_PROCESSING_TIME, processingTime);
                db.insert(TABLE_PROFILE,null,values);

                db.close();
            }
            catch(Exception e)
            {
                Toast.makeText(mContext,
                                        "Error in Inserting to Database",
                                         Toast.LENGTH_LONG).show(); 
            }
        }
    }

Upvotes: 0

Views: 725

Answers (2)

DwB
DwB

Reputation: 38290

Steps to solve your issue:

  1. Add a language tag to your question. Your code looks like Java, but I don't recognize Toast.
  2. Google search for "format date in java". A Google search is ALWAYS the best place to start when attempting to find a java solution (other solutions as well).
  3. Find, then read the SimpleDateFormat API Page (JSE 6.0 SimpleDateFormat Page).
  4. Write a test program to figure out how to use SimpleDateFormat.
  5. Use SimpleDateFormat.

Here is some example source:

Date date = null;
final String dateValue = "12Nov2013";
final DateFormat dateFormat = new SimpleDateFormat("ddMMMyyyy");

try
{
    date = dateFormat.parse(dateValue);
    System.out.println("Parsed Date: " + date);
}
catch (ParseException exception)
{
    System.out.println("ParseException: " + exception);
}

Upvotes: 0

Bart Enkelaar
Bart Enkelaar

Reputation: 694

JodaTime is excellent for working with dates in Java

Upvotes: 1

Related Questions