I'm having an issue when storing a date to my local SQLite database in my Android App.
I am using a global date format:
public static final String DATEFORMAT = "yyyy-MM-dd HH:mm:ssz";
Once I have retrieved a date from my Azure database and I then format it to a string so it can be stored in a SQLite database.
row.put(Constants.COL_DATE_START, (String) DateFormat.format(DATEFORMAT, DateStart));
It all seems to work fine except for instead of 2013-09-18 13:00:00+0000 I am getting:
2013-09-18HH:00:00+0000
For some reason it won't pick up on the 'HH' being an hour number. If I change it to 'hh'
it gives me 2013-09-18 01:00:00+0000 - leaving me 12 hours off.
Any ideas? Any help would be greatly appreciated!!
Try this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateFormat = sdf.format(yourDate); //java.util.Date
row.put(Constants.COL_DATE_START, dateFormat);
I usually store a timestamp and format the date when I'm showing it. I know it doesn't answer your question directly but AFAIK it is considered best practice.
Related
I have an SQLite database in an Android project with a Date column that stores the date-time as String in dd-mm-yyyy HH-mm-ss format. I need to sort it based on the descending order of the date.
Or, convert it to the standard yyyy-MM-dd HH-mm-ss format and then sort it.
The general ORDER BY DATETIME(coulmn_name) doesnt work.
NOTE:
This is not a duplicate question, other answers advice to change the database schema (Which is not possible, because I have data stored already)
I would like to suggest an alternative approach to the one you are taking. I personally ran into the same issue and solved it by not using a string date at all.
Instead i converted the date to epoch milliseconds ie unix timestamp and saved that. Then a sort is a simple order by the timestamp.
You can use the following approach:
SimpleDateFormat sdf = new SimpleDateFormat ("dd-MM-yyyy HH:mm:ss");
Date currentDate = sdf.parse(yourdatestring);
//Get the calendar in the time zone you need, generally it works off the bat with the default time zone
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("yourtz"));
cal.setTime(currentDate);
//Get the milliseconds since epoch time
long millis = cal.getTimeInMillis();
You can save this timestamp and easily sort it. It'll be more accurate and easy to use than a string and potentially gives you the ability to handle different time zones.
You can retrieve the date by setting this timestamp directly in the calendar and getting a date from it
cal.setTimeInMillis(timestamp).getTime();
Hope this helps
How do you convert a date to the date format of the device? For example, I have following date: 02/11/2011 (mm/dd/yyyy). How to convert it to the format of the device?
DateFormat has the static methods getDateTimeInstance, getTimeInstance and getDateInstance that are already localized
You might want to consider storing your dates in a more locale-agnostic way as milliseconds.
Then you can use DateFormat.getDateFormat() like this:
dateTextView.setText(DateFormat.getDateFormat(getActivity()).format(new Date(millis)));
According to the documentation for getDateFormat():
Returns a DateFormat object that can format the date in short form (such as 12/31/1999) according to the current locale and the user's date-order preference.
Use SimpleDateFormat to convert a Date into required format.
See this link for more details..
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String formattedDate = format.format(yourdate);
I insert date in sqlite database in a supported format (yyyy-mm-dd).
Now I would like the user at the time of the query to display the date format according to country (Italy dd-mm-yyyy, America yyyy-mm-dd etc ...)
How do I? Thanks
SQLite does not have a dedicated date and time data type. If you insert something like "01-01-2013" it will be stored like that, as a string, making comparisons, sorting and queries difficult and slow because you need to run conversions on that using SQLite date functions.
You should store UNIX timestamps instead. That requires the date column to be of type INTEGER. Timestamps can be quickly handled, sorted and selected and you can represent them in any date format you wish by using Java's Calendar and DateFormat classes, for example. You can retrieve an appropriate format for the user's default locale through factory methods.
On top of that there's Android's dedicated DateUtils class that provides various functions for creating date-time and time range strings in the user's locale.
You can also use the SQLite date and time formatter, something like:
SELECT strftime( '%d-%m-%Y', birthday) as birthday FROM people
Try the following code,
String date = "2013-11-15"; // Retrived date in your specified format from sqlite
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date res = null;
try {
d = (Date)sdf.parse(date);
} catch (Exception ex) {
ex.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(d);
String day = c.get(Calendar.DAY_OF_MONTH);
String month = c.get(Calendar.MONTH);
String year = c.get(Calendar.YEAR);
//You can use these day, month and year string values to view in any format
Hope this will help you. Thank you.
I've got following string "2013-04-30T00:55:25.855-07:00" from Google blogger feed. I try to save this string to SQLite datetime field as following command
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
initialValues.put(newsdatemodified, dateFormat.format(datemodified));
But I found that data cannot insert into sqlite table and no encounter any errors. Any solution will be appreciated.
Update
When I've tried to use following coding
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date1 = (Date) dateFormat.parse(entry.updated);
but following this error
05-02 09:56:05.383: E/AndroidRuntime(31634): Caused by: java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
Your format is wrong, it needs to me yyyy-MM-dd'T'HH:mm:ss.SSSZ
as you can see the format you had does not match what the incoming string format was
It seems that issue is with the format. May be, you can try using yyyy-MM-dd'T'HH:mm:ss.SSSZ. SSS stands for fractional seconds and Z stands for time zone.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Hope it helps else please comment. You can see other formats and try to work around with them by seeing here.
In my appliaction I have to store current date into the database. How can i get the current date and is there is any specific format to store date in database.
Better would be to store the date/time in long in Database and then fetch the long date/time from Database and specify the required format using SimpleDateFormat.
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in
Greenwich on November 24, 4714 B.C. according to the proleptic
Gregorian calendar.
INTEGER as Unix Time, the number of seconds since 1970-01-01
00:00:00 UTC.
Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.
Now for how to insert date in after it.
Use PreparedStatement#setString() or #setLong() respectively.
Hope this explanation works for you..
first convert the date to be stored to a String object using SimpleDateFormat class
code sample:
Date dateToBeStored = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); // this format will help you to convert date to 2012/07/04 format string
String dateString = formatter.format(dateToBeStored); // convert string
now read the date string from DB. you should have some means to get the date back from DB.
String readDateStringFromDB = readDate();
Now parse the read date string to date object by parse method of SimpleDateFormat class
Date dateObj = formatter.parse(readDateStringFromDB); // now you have the Date object back
SimpleDateFormat sdfDateTime = new SimpleDateFormat("dd/MM/yyyy"+ "",Locale.US);
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
You can use the Date class to get the epoch time, which could then be stored in the database as an integer. Alternatively you could convert the epoch time to regular time and store it as a date data type.
https://developer.android.com/reference/java/text/SimpleDateFormat