mcr619619
mcr619619

Reputation: 435

Inserting datetime in sqlite database android

how can i insert datetime data in my sqlite database using contentvalues not using raw query?.

datetime('now') insert itself(text) not the time, and can i add addittional hours to the current time?

like, when i press button "1HOUR" it would insert the currenttime + 1 hour in the sqlite database..thanks, kinda confused..

Upvotes: 6

Views: 19563

Answers (2)

Luis
Luis

Reputation: 12058

Convert date/time to milliseconds and you get a long. Then you just insert the long value in database.

You can add date/time values together if they are in milliseconds.

--EDITED--

    Date myDate = new Date();
    long timeMilliseconds = myDate.getTime();
    //add 1 hour
    timeMilliseconds = timeMilliseconds + 3600 * 1000; //3600 seconds * 1000 milliseconds
    //To convert back to Date
    Date myDateNew = new Date(timeMilliseconds);

In SQLite the java long value is stored as a int.

Upvotes: 6

RajeshVijayakumar
RajeshVijayakumar

Reputation: 10650

You cannot use the datetime functions using the Java wrapper "ContentValues". You can implement in this ways :

1) You can useSQLiteDatabase.execSQL (raw SQL query)

 dbObj.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) ");

2) You can use SimpleDateFormat

// setting the format to sql date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date date = new Date();
ContentValues initialValues = new ContentValues(); 
initialValues.put("date_time", dateFormat.format(date));
long recordId = mDb.insert(DB_TABLE_NAME, null, initialValues);

3) you store date value in database as (long type) milliseconds and for displaying you can format it,

 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;

System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS"));

// Return date in specified format.
// milliSeconds Date in milliseconds
// dateFormat Date format 
// return date as string in specified format

public static String formatDate(long milliSeconds, String dateFormat)
{

    DateFormat formatter = new SimpleDateFormat(dateFormat);

// Create a calendar object that will convert the date and time value in milliseconds to date. 
   Calendar calendar = Calendar.getInstance();
 calendar.setTimeInMillis(milliSeconds);
 return formatter.format(calendar.getTime());
   }
 }

1 Second = 1000 Milliseconds, so if you want to add 1 hour then use this formula

  currentTImeMilli + (60 * 60 * 1000)

Upvotes: 2

Related Questions