Inserting datetime in sqlite database android - 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..

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.

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)

Related

Android GreenDao - How to compare to two date strings?

I have few string properties with custom type java.util.Date added in MainGenerator class.
In querybuilder how can I compare these strings with ge or le or gt or lt.
I save the db values in string type and I compare them like this
qb.queryBuilder().where(TestDao.Properties.Date_entered.ge(start)).list();
It doesn't work.
If you are using greenDao then in your MainGenerator you must be having the date as
testdao.addDateProperty("date_entered").notNull();
So in qb.queryBuilder().where(TestDao.Properties.Date_entered.ge(start)).list();
start should be java.util.Date.
Dates are persisted as timestamps of type long. Thus, for your query parameters, you should also use long values.
First Parse your date in String as you are saving date in database in string format. Then query data. Here is sample code.
SimpleDateFormat dateFormat;
Calendar calendar = Calendar.getInstance();
//Modify Calendar here according to your requirement.
dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//Check if you have different date format then replace in above line.
String dateString = dateFormat.format(calendar.getTime());
//Then query your data
qb.queryBuilder().where(TestDao.Properties.Date_entered.ge(dateString )).list();
You can convert String date into milliseconds and can compare the values for your result:
public boolean checkDates(String date1, String date2) {
long milliDate1 = getMilliFromDate(date1);
long milliDate2 = getMilliFromDate(date2);
//Check date according to your requirement and condition
return milliDate1 < milliDate2;
}
public long getMilliFromDate(String dateFormat) {
Date date = new Date();
// "dd/MM/yyyy" this is date format i use you can use your own
//format which you are storing in local database like time stamp "yyyy-MM-dd HH:mm:ss"
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
date = formatter.parse(dateFormat);
} catch (ParseException e) {
e.printStackTrace();
}
return date.getTime();
}

Compaire sqlite database date string "yyyy-MM-dd" with todays string in android?

I am storing from_date and to_date column in the database as sdf (yyyy-MM-DD). And I want to check if todays date is between these two dates or not.
My query is:
String where = Alarm.COL_TIME+" = "+"'"+time+"' AND Date(from_date) <= Date ('"+ today +"') AND Date(to_date) >= Date ('"+ today +"')";
But it shows nothing.
Please neglect time
how to do this??
Lets say You have a String as a Date like You said "yyyy-MM-dd". Lets say it´s "2014-12-03". Then, parse it to a long value with:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
String todayString = "2014-12-03";
String fromString = "2014-12-01";
String toString = "2014-12-05";
Date todayDate = format.parse(todayString);
Long today = todayDate.getTime();
Date fromDate = format.parse(fromString);
Long from = fromDate.getTime();
Date toDate = format.parse(toString);
Long to = toDate.getTime();
With this You have all three long values and can compair:
if(today>fromDate&&today<toDate){
//then today is between these days
}
The following code will store today's date in your today variable, in yyyy-MM-dd format:
// Imports
import java.text.SimpleDateFormat;
import java.util.Date;
// Above your "String where = Alarm..." assignment
String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

To convert Long integer value into date

I am downloading some JSON data from a web service. In this JSON i get the Date values like "Date=1423131814.0"
This is the Date/Time on which the image is getting uploaded. Now, I need to get the original Date/Time from above returned number.
and then I also need to display the hour only same as Facebook, like 5 hrs ago, yesterday at 2:30 PM.
/**
* Return date in specified format.
* #param milliSeconds Date in milliseconds
* #param dateFormat Date format
* #return String representing date in specified format
*/
public static String getDate(long milliSeconds, String dateFormat)
{
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
And invoke this method as getDate(millis, "dd/MM/yyyy hh:mm:ss.SSS")

comparing milliseconds with data in android

I have data+time in saved in database (sq lite) in milliseconds, now I want to get data from sq-lite of a specific date and I have date in this format "26-December-2012", how to compare this with milliseconds.
what should be the query to fetch data from database?
You have to convert the milliseconds into date format then compare two dates
convert into date formate
public static String getDate(long milliSeconds, String dateFormat)
{`enter code here`
// Create a DateFormatter object for displaying date in specified format.
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());
}
compare dates
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = curFormater.parse(date1Str);
Date date2 = curFormater.parse(date2Str);
if (date1.before(date2))
{
}
Simply create a new Calendar with the timeInMilliseconds data from the database.
So, if you have the time in a column called date and the data is in a table called myTable the query to get that is:
select date from myTable ... other constraints
In android, simply use the long value retrieved from the database to construct a new Calendar:
Calendar cal = new Calendar.getInstance();
cal.setTimeInMillis(timeInMsFromDatabase);
Once you have a Calendar object, you can retrieve the values you want with the get(int field) method.
Or, you can use the DateFormat class.
Make sense?
I hope this will be helpful to you
public long getDateLong(String dateString, String format) throws ParseException
{
SimpleDateFormat f = new SimpleDateFormat(format);
Date d = f.parse(dateString);
return d.getTime();
}
//
long timeMillis; // Your long time millis
boolean compare = timeMillis > getDateLong("26-December-2012", "dd-MMMM-yyyy");

Format date for SQLite and subtract minutes

I need to subtract an X number of minutes from the current date and format it for a SQLlite query in my Android app. This is what I have so far:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -60); //one hour back
final SimpleDateFormat std = new SimpleDateFormat("yyyy-mm-dd hh:mm");
std.setCalendar(cal);
String date = std.format(cal.getTime());
String sql = "SELECT * FROM [tbl_name] WHERE [datefield] >= " + date;
datefield is stored as a DATETIME in the SQLlite table. I don't want to use Joda time because I want to keep the number of dependencies in my app to a minimum.
With my current code, the date date variable is coming out as: '2012-43-05 07:43'
You are using minutes twice in your format. mm actually needs to be MM in the date portion.
final SimpleDateFormat std = new SimpleDateFormat("yyyy-MM-dd hh:mm");

Categories

Resources