I have a Database that when ever i put in information about things i want the database to show a time stamp with the information that i put in.
I'm assuming when you say "put in information" you're talking about an insert. If that's the case, you can just create a datetime column with the default of now in your schema:
DATETIME DEFAULT CURRENT_TIMESTAMP
You can also set it on your insert:
INSERT INTO your_database VALUES (datetime())
See here for more details:
How to insert a SQLite record with a datetime set to 'now' in Android application?
Good luck!
The simplest option might be to do it manually. Add an integer column and store System.currentTimeMillis() in that column.
EDIT
If you want to store it human readable create a text column. Then create the timestamp something like this
SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy HH:mm:ss.S z");
Date now = new Date();
String timestamp = sdf.format(now);
which creates a String like this (you can change the format, check out the SimpleDateFormat documentation)
9 Dec 2011 23:06:05.849 EST
and if you are reading from the database you can do this to get a date object
Date then = null;
try {
then = sdf.parse(timestamp);
} catch (ParseException e) {
e.printStackTrace();
}
If you don't really care about the format you can just do
String timestamp = new Date().toString();
which will give output like
Fri Dec 09 23:06:05 EST 2011
Related
I'm trying to see how I can compare if the new date is after the old date if so no data will be shown from the firebase database. I am having trouble with this because my app crashes when I test it I believe I'm doing something wrong. Can someone help me with this issues? Below is my code. Thanks in advance
//Code
if(dataSnapshot.exists()){
//progressBar.setVisibility(View.GONE);
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
UserInformation2 upload=postsnapshot.getValue(UserInformation2.class);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("M-dd-yyyy");
//String now = simpleDateFormat.format(new Date());
Date d=new Date();
String AdCreationDate = postsnapshot.child("created").getValue(String.class);
//SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd")
try {
Date new_date = simpleDateFormat.parse(String.valueOf(d));
Date old_date = simpleDateFormat.parse(AdCreationDate);
if(new_date.after(old_date)){
// Your time expired do your logic here.
Toast.makeText(getContext(), "Your data expired", Toast.LENGTH_SHORT).show();
}else{
myUploads.add(upload);
recyclerView.invalidate();
}
} catch (ParseException e) {
e.printStackTrace();
}
//simpleDateFormat.format(d);
//Date e=new Date(old);
}
linearLayoutWithoutItems.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
Stacktrace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.tout, PID: 22667
java.lang.IllegalArgumentException
at java.util.Date.parse(Date.java:638)
Your error isn't in the comparison, it's in the String old = simpleDateFormat.format(new Date(Date.parse(AdCreationDate)));
Check the value of AdCreationDate it might not be compatible with a list of valid date formats that can be parsed, at the very least you can place AdCreationDate into a SimpleDateFormat and then parse that.
You need to change this logic. When working with dates it's always better to work with timestamp. This is easy to convert to date or anything else and also easy to compare between dates.
So, when you are saving your date to the database just save it as
long timestamp = date.getTime(); //this will return time in milliseconds
Then when you retreive the values from database, you don't even have to format them before checking which one is older. You can simply use this:
long database_timestamp = postsnapshot.child("created").getValue();
long current_timestamp = System.currentTimeMillis();
if (current_timestamp > database_timestamp) //this will check if current_timestamp has greater value then database_timestamp, if it has it means that it's date from later in time
Now you can simply convert that to date and use SimpleDateFormat to format it as you want:
Date new_date = new Date(current_timestamp);
SimpleDateFormat format = new SimpleDateFormaT("MM-dd-yyyy");
This also covers each hour, second, minut,e or anything else you need. So, this will also check if the current date is greater than the other one even if there is only a few seconds difference between them. Which means your data will be live. If you don't need this you can also avoid it by setting the hour, minutes, and seconds on the Date to 0.
It looks like the error is actually related to
Date new_date = simpleDateFormat.parse(String.valueOf(d));
If you comment out that line and then update the if statement to
if(d.after(old_date)){
You don't need to parse the new date as it's already a Date object. You only need to parse the date from your snapshot as it is a string.
I'd also change the new date variable d to something more meaningful as it well help the readability of the code and the Java standard for naming variables is to use camel case where the scond word is capitalised without an underscore i.e. 'oldDate'. It's good to get into the habit of following these conventions.
I am working on an app where I am saving date in currentTimeMillis() in sqlite database and when I read it I try to convert it to readable format. But date is always being converted to Jan 01, 1970.
Following is my code of Saving it to sqlite database:
long date = System.currentTimeMillis();
I then try to convert it to readable format in following way:
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(attendance.getPicDate());
Date resultdate = new Date(attendance.getPicDate());
System.out.println(sdf.format(resultdate));
I am getting the following output:
Jan 17,1970 19:36
Edit1: attendance.getPicDate() value = 1432678159
Edit2: when I try to save value it is 1500378235812 but when I read it, it becomes above, My column in table is Integer.
1432678159 does convert to Jan 17,1970 19:36.
Try checking attendance.setPicDate().
I found my mistake I was using cursor.getInt(2) to fetch date from database but now I have corrected it to cursor.getLong(2) and it is working great now.
I suggest, you should save date and time in string format in database.
Calendar calendar=Calendar.getInstance();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
String currentTime=sdf.format(calendar.getTime());
save that "currentTime" in your database.
"I try to compare two time in "hh:mm:ss a" format. But it not really work in what I think. I googled but couldn't find a proper answer. Sorry cause I'm new to programming."
I try to compare the time like this:
String strSQL = "SELECT * FROM " + TABLE_SCHEDULE + " WHERE lecturer_id=? AND schedule_day=? AND schedule_endtime > ?";
schedule_endtime > ?
However, the comparison has ignored the AM/PM which caused the result become like this:
eg. 12:00:00 PM is bigger than 02:00:00 PM.
Hope that you all can give some tips or provide some solution. Appreciate it.
Instead of comparing the formatted string, compare the value in milliseconds. Take a look at this to convert the string back to date:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Then once you have two dates you can compare them like so:
boolean before = someDate.before(anotherDate);
or
boolean after = someDate.after(anotherDate);
or even
someDate.getTime() < anotherDate.getTime();
Side note: when I store dates, I like to just store the millisecond value and the time zone. That way you don't need to worry about things like this.
Inside the SQLite database you are storing the dates as Strings, not as a Date because in SQLite doesn't exist a Date type (https://www.sqlite.org/datatype3.html).
You have two options: change the column type to a INTEGER type and store de date as a number (then you can compare milliseconds) or get the entity as it is, parse a Date type with the String, create a SimpleDateFormat with the given format and then make the comparison.
I want to have a search between specific dates. Say for example from the 1st of Aug 2012 to 13th Aug 2012. Search on this criteria gives me the entered value in the DB. If I make it 2nd Aug 2012, the query returns me null...Even weirder is that when I select 10th, 11th or the 12th Dates it works fine and gives me results...I have gone crazy trying to know where the issue could be and debug has not lead me any where....Help please?
/**query to get the details by giving all the dates/
public Cursor getName_Intime_Outtime_Date(String fromdate,String todate)
{
Log.d("pavan","in side the getnameintime out time date() of visistor adapter");
return this.db.query(DATABASE_TABLE_VISITOR,
new String[]{KEY_NAME,KEY_CHECKIN,KEY_CHECKOUT,KEY_DATE},
KEY_DATE + " BETWEEN ? AND ?",
new String[] {fromdate ,todate},
null, null, null, null);
}
Sqlite doesn't have a data type for dates. Probably you save your date as TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
I recommend you save date fields in your table as sqlLite datatype INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC, or as BIGINT (long java time version in miliseconds).
This way you would have a corect value returned when using BETWEEN with numbers.
EDIT
You can manage your date string from your query using date and time functions. This means you can still use your dates as strings, but performing casts to "DATE" using conversion functions when stringDates are used in sql WHERE clause.
try this, it is working for me, SELECT * FROM table_name
where substr(column_name,7)||substr(column_name,4,2)||substr(column_name,1,2)
between 'YYMMDD' and 'YYMMDD' , dates should be in reverse order eg: if date format is DD/MM/YY or DD-MM-YY , you can use 'YYMMDD'
Thank you guys for really looking into this...Finally solved this using idea found in this link https://groups.google.com/forum/?fromgroups#!topic/android-developers/Ey_4rBZx2t0%5B1-25%5D ....to summarize what I did was take a Calendar object, retrieve the current date using the Calendar object, the retrieved data is given to a simpledateformat object and comparisons to be made on that....Here is the sample code...
int test = date_pick.getMonth()+1;
Toast.makeText(getBaseContext(), "Date seleted month"+test+"/"+date_pick.getDayOfMonth()+"/"+date_pick.getYear(), Toast.LENGTH_LONG).show();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.YEAR, date_pick.getYear());
cal.set(Calendar.MONTH, test);
cal.set(Calendar.DAY_OF_MONTH, date_pick.getDayOfMonth());
/* retriving the yyyy mm dd values here*/
set_year = cal.get(Calendar.YEAR);
set_month= cal.get(Calendar.MONTH);
set_day = cal.get(Calendar.DAY_OF_MONTH);
Log.d("kunal","datesis "+set_year+" "+set_month+" "+set_day);
string_date = set_year+"-"+set_month+"-"+set_day;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
try {
d1 = sdf.parse(string_date);
Log.d("kunal","date came "+d1);
System.out.println(sdf.format(d1));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
date_txt.setText(sdf.format(d1));
i am working on data manipulation using sqlite.
how can i insert the datetime value in sqlite
i implemented the below code in my app.
it works,
SimpleDateFormat curFormater = new SimpleDateFormat("dd-MMM-yyyy",Locale.ENGLISH);
Date dateObj = null;
dateObj =curFormater.parse(txt_date_start.getText().toString());
SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
String newDateStr = postFormater.format(dateObj);
but I want to store as "2011-Jul-13 05:15 PM",ple give me example..
thanks in advance
in sqlite you dont have any data type as date or time.while creating the column u have to specify any one of the text,int or real data type.then while inserting make use of the date and time funcs of sqlite.
Create column in sqlite's table with type TIMESTAMP/DATE and put the date in UNIX timestamp.