Android Format Date from SQLite - android

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.

Related

Sort a column with string format dd/MM/yyyy in SQLite (Android)

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

SQLite isn't returning correct records based on a date

I have four buttons on an android app i'm making.
Each button queries an SQLite database and grabs records based on a date. (Buttons are 'Today', 'Week', 'Month', 'All')
The date is stored as a DATETIME in my table, and i'm querying it with a date as well. Everything works well, until i'm grabbing everything that's been done ahead of the previous month.
Example
Todays date is June 29th 2016
I create an entry on June 16th 2016 into my SQLite Database and it stores successfully. I create another entry on June 27th 2016 and it stores successfully.
Now I press the 'Today' button and return 0 records. (Correct)
I press the week button and return 1 record (Correct - Created on June 27th)
I press the month button and return 0 records. (Incorrect. I should be getting 2 records)
The Code
This is the query I use for my database:
String queryString = "SELECT * FROM job_quote_lookup WHERE created_at >= '" + date + "' ORDER BY created_at ASC"
The 'date' is calculated like so:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -31);
Date fromDate = cal.getTime();
date = dateFormat.format(fromDate);
(31 represents the largest possible number of days in a month period)
It seems that the problem occurs when the date goes back a month. If I remove 20 days instead of 31, the date will "June 9th" and i will receive BOTH records as i should. But if the date goes into May, i will receive 0 records.
Other queryStrings i have tried
String queryString = "SELECT * FROM job_quote_lookup WHERE created_at >= date('now','-31 days') ORDER BY created_at ASC"
This didn't seem to work?
I'm still new to Android so apologies if it's a bad question. I have googled around but haven't found anything that might help.
UPDATE: Extra Info
Here is some additional code that might be more helpful
The dateFormat used to time stamp entries into my SQLite is:
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy - HH:mm", Locale.getDefault()); //"yyyy-MM-dd HH:mm:ss" - "dd-MM-yyyy HH:mm:ss"
Date date = new Date();
return dateFormat.format(date);
}
The date format used when i'm querying my database is:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
I'm not sure if this is correct, however my reasoning for leaving "HH:mm" off was due to the "Today" option not working correctly as it would return everything greater than the current time (which is obviously nothing in terms of time stamping)
Unable to solve...Ended up converting my database DATETIME to INTEGER and storing the date in milliseconds then just converting between date format and milliseconds to query and display information.
If you want to alter the month of a Java Calendar object you will need to use:
cal.add(Calendar.MONTH, -1);
where the above snippet would roll the month back by one. If you call cal.add(Calendar.DATE, -31) on February 15, for example, you get a weird result because the month won't change but the day will roll over.
Update:
You also have to make sure that the date format you feed into MySQL is correct. MySQL expects the format YYYY-MM-DD for dates, so use this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(cal.getTime());
I recommend using JodaTime if you expect complex calendar operations.

Date format issue with 'HH' when storing to SQLite Database

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.

Date and time in android

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

Trouble converting back from int to DateTime

I am returning data from a sqlite3 database the some else wrote. I am trying to retrieve the date and time. To store it into the db I converted the date and time into one int. using this line
int currentTime=(int) ((newTime).toMillis(true) / 1000);
I am able to retrieve the data as an int, but cannot figure out how to convert the number back into a
date and time. Currently the db returns int 13333380180, I am trying to convert it to today's date and time.
long yourmilliseconds = 13333380180;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));
Use the above code to convert
The number you're receiving is the number of milliseconds that have passed since January 1st, 1970. It's a standard, consistent way of representing a date & time on a number of platforms.
Although the value is an integer in SQLite, SQLite integers can be up to 64 bits. So, the value being returned to you should be treated as a long in Java. You can convert it to a Java Date object in a straightforward fashion: new Date(currentTime).

Categories

Resources