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");
Related
I'm having a problem inserting some datetime values in my sqlite database.
I have two datepickers, i can choose a date, but after that, when I insert it into my database, I don't know why but the row for the 2 dates have the current date.. How can I do to insert the date I selected in the datepicker ?
In my database, I declared those columns as DATETIME.
Here's my get-setter class for the dates:
public String getDate_debut() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public void setDate_debut(String date_debut) {
this.date_debut = date_debut;
}
public String getDate_fin() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public void setDate_fin(String date_fin) {
this.date_fin = date_fin;
}
Here's how I get the date of one datepicker. I'm not sure about the way I format my string, and if I need to format or if I can just add as a string.
private DatePickerDialog.OnDateSetListener datepickerdernier
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
year_x2 = year;
//les DatePicker
month_x2 = month +1;
day_x2 = dayOfMonth;
datefin = (TextView)findViewById(R.id.TVDatePickerDernier);
datefin.setText(year_x2+"-"+month_x2+"-"+day_x2);
}
};
String date2 = datefin.getText().toString();
//im not sure about the following lines
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date_dernier = dateFormat.parse(date2);
And at the end I insert it :
Cours c = new Cours();
c.setBranche_cours(selectedBranche);
c.setDate_fin(date2); //should i set the string ?
dbhelper.Open();
dbhelper.insertCours(c);
How can I insert in my db the date I selected and not the current date?
#UPDATE - **How can I update the date that is inserted ?
I have another activity, and i want to modify the dates I chose before, but I'm not able..
Here's my sqlite method :
public void updateCours(Date olddatedebut, Date newdatedebut, Date olddatedernier, Date newdatedernier)
{
Open();
db.execSQL("UPDATE "+TABLE_COURS+" set "+COLONNE_DATEPREMIER+"=date('"+newdatedebut+"') where "+COLONNE_DATEPREMIER+"=date('"+olddatedebut+"')");
db.execSQL("UPDATE "+TABLE_COURS+" set "+COLONNE_DATEDERNIER+"=date('"+newdatedernier+"') where "+COLONNE_DATEDERNIER+"=('"+olddatedernier+"')");
}
And how I pass that to my method on my activity:
//this is the new date of the 2nd datepicker
String datedernier = convertDateFormat(datenew2, "yyyy-MM-dd", "dd-MMM-yyyy");
//this is the new date of the 1st datepicker
String datepremier = convertDateFormat(datenew1, "yyyy-MM-dd", "dd-MMM-yyyy");
String date_debutold= intent.getExtras().getString("date_debut");
String date_finold=intent.getExtras().getString("date_fin");
//this is the current date recorded in my database from my datepicker
String date_debut1= convertDateFormat(date_debutold, "yyyy-MM-dd", "dd-MMM-yyyy");
//this is the current date recorded in my darabase from my 1st datepicker
String date_fin1= convertDateFormat(date_finold, "yyyy-MM-dd", "dd-MMM-yyyy");
//nouvelledatedebut
Date date_premier= new Date(datepremier);
Date date_dernier = new Date(datedernier);
Date date_premier2 = new Date(date_debut1);
Date date_fin2 = new Date(date_fin1);
dbhelper.Open();
dbhelper.updateCours(selected_brancheold,selectedBranchenew,date_premier2,date_premier,date_fin2,date_dernier,
Thats because you are making some logic on the getter method and setting the new Date(), that will override the date on the date_fin attribute. When you make insertCours probabily this method will try to find all the get methods for the object you are trying to insert. Try change this:
public String getDate_fin() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
Date date = new Date();
return dateFormat.format(this.date_fin);
}
to this
public String getDate_fin() {
return this.date_fin;
}
If you still want to add a format to the Date (String), you can still make it on the getter method, but I don't recommend it.
try this
public static String convertDateFormat(String date, String curFormat, String desFormat){
String newFormat = null;
Date frmtDate = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(curFormat);
frmtDate = sdf.parse(date);
SimpleDateFormat formatter = new SimpleDateFormat(desFormat);
newFormat = formatter.format(frmtDate);
} catch (Exception e) {
newFormat = date;
}
return newFormat;
}
sample
String result = convertDateFormat(date2, "yyyy-MM-dd", "dd-MMM-yyyy");
c.setDate_fin(result);
Each value stored in an SQLite database (or manipulated by the
database engine) has one of the following storage classes:
NULL. The value is a NULL value.
INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8
bytes depending on the magnitude of the value.
REAL. The value is a floating point value, stored as an 8-byte IEEE
floating point number.
TEXT. The value is a text string, stored using the database encoding
(UTF-8, UTF-16BE or UTF-16LE).
BLOB. The value is a blob of data, stored exactly as it was input.
There is no DATETIME. SQlite store it as a TEXT. You can't add a day. You have to read it and parse it. And the same goes when you store it. You have to parse it.
Hope it was usefull.
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();
}
I have to get count of days which are past to the current day.I have list of days in arraylist.I got the list and I dont know how to compare?Can anyone help me?
This is the code I tried,
private void weeklylogeval(){
int i;
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormatter.setLenient(false);
Date today = new Date();
String s = dateFormatter.format(today);
System.out.println("current date & time new:::"+s);
for(i=0;i<datetime.size();i++){
String daytime=datetime.get(i);
if(today.before(daytime))
}
}
Pls some one help me!
Try this code for date difference manipulation.
String fd=from_date;//date get from mysql database as string.
String td=to_date;//Today's date as string.
if(!fd.equalsIgnoreCase("") && !td.equalsIgnoreCase("")){
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat formatter;
Date frmdt=new Date(fd);
formatter = new SimpleDateFormat("dd/MM/yyyy");
String s1 = formatter.format(frmdt);
Date todt=new Date(td);
String s2 = formatter.format(todt);
Date frmdate = sdf.parse(s1);
Date todate = sdf.parse(s2);
if(frmdate.compareTo(todate)<=0) {
//do your stuff
} else {
// do your stuff
}
}
http://developer.android.com/reference/java/util/Calendar.html
This should be allot easier to use for your purpose
Edit:
Methods you can use:
boolean after(Object calendar)
Returns whether the Date represented by this Calendar instance is after the Date represented by the parameter.
boolean before(Object calendar)
Returns whether the Date represented by this Calendar instance is before the Date represented by the parameter.
Maybe you can construct a Date form the String you get from DB, and then use today.before(daytime) to compare them.
Date daytime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(datetime.get(i));
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)
I have a requirement that I need to compare two Dates. One Date will come from DB which is String in "YYYY-DD-MM" firm and I need to compare this String Date with current Date.
for this I am converting Date String into Date object.
Now I need current Date also in "YYYY-MM-DD" format and it should be Date object so that I can use.compareTo() method compare two dates..
Please help me how to do that...
Date cDate = new Date();
String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
You can do it in following way
// pick current system date
Date dt = new Date();
// set format for date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// parse it like
String check = dateFormat.format(dt);
System.out.println("DATE TO FROM DATEBASE " +
arrayOfStringDate[d].toString());
System.out.println("CURRENT DATE " + check);
// and compare like
System.out.println("compare "+
arrayOfStringDate[d].toString().equals(check));
Calendar c = Calendar.getInstance();
SimpleDateFormat tf = new SimpleDateFormat("yyyy-MM-dd");
String time=DB time;
Date parseTime= tf.parse(time);
Integer dayNow=c.getTime().getDate();
Integer dayDb=parseTime.getDate();
then you can compare dayNow and dayDb.
If your current date is actually an instance of the java.util.Date class, you don't need to specify a format for it; it's just a millisecond value that represents a specific moment in time.
You can get the current date like so:
Date currentDate = new Date();
You can use 2 ways:
DateFormat object. Use parse method.
Make your own parser of the Date. I mean, you convert the year, month and day in an integer each, and use Date constructor to get the Date.