Sqlite: select ('now') not works as expected - android

I want to get the current date as yyyy-MM-dd from SQLite, I use the following query:
***SELECT date('now')***
But instead of returning the current date, it returns the next day from today.
For example, today (2015-12-01) I run the query and it returns (2015-12-02).
What I did wrong?
Image running query + calendar

sqlite date and time functions use UTC time zone internally. In UTC the date was already 2015-12-02.
If you want to use another timezone, you need to specify it explicitly, e.g.
select date('now','-05:00');
I'd suggest to use UTC millisecond timestamps in your database layer though and have the presentation logic such as date formatting with timezone adjustment in your app code.
Reference: https://www.sqlite.org/lang_datefunc.html

Related

how to change timezone without affecting the saved time in currentTimeMillis()?

so, let's say I want to save a data in my database and save the timestamp (date and time) for the time the data saved in database. for example in +3:00 GMT.
now the timezone changed and the saved time when I getting it is changing too but I don't want that.
I want it to show the time in that timezone not current
and I using currentTimeMillis() for getting time
it's my code of getting time
val timeStamp = System.currentTimeMillis()
and code for getting from database in my view holder
val tsLong = currentItem.timeStamp
System.currentTimeMillis will always report in UTC regardless of the user's timezone.
I would recommend using Instant to store all your timestamps. Instants can easily be converted to any timezone. Instant has the following advantages:
Explicitly always in UTC/GMT timezone
toString() to ISO date format that is much more readable than milliseconds from the epoch
Far too often when we use milliseconds from the epoch we can't easily read them and it's ambitious if the field is seconds from the epoch or milliseconds. using Instant removes this ambiguity and makes things easier for developers.

How to query if the day of the start date > the day of the end date?

I use LocaleDate.now in Android to get data from Sqlite based on the start date of week and the end date of the week. For example, if start date is 20/07/2020, then the end date will be 26/07/2020. I will get data from range date betwwen 20/07/2020 and 26/07/2020. My code run fine until today, i get start date of this week is 27/07/2020, the end date is 02/08/2020. I surprised because i couldn't get the data from sql, so i debugged and i realized the Sqlite couldn't get the data from range date between 27/07/2020 and 02/08/2020. I think if the day of start date(27) > the day of the end date(2) then Sqlite can't query it. How to solve this problem?
SELECT name
FROM date_detail
where date BETWEEN '27/07/2020' and '02/08/2020'
//not show me anything
I think you can solve this problem by saving dates into database in another format, such as 'yyyy-mm-dd' or with timestamp, so it can select dates between two dates.

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

How to store current locale date and time in SQLite

..and later retrieve and show them as Strings?
I'm asking the user some input and I want to store both the date (i.e., day, month and year) and the time (i.e., the hour of the day) this input was submitted. Each submission is then saved in my SQlite database, and later retrieved from a RecyclerView.
I'm facing two problems at least. Right now I set up two TEXT fields in the database, FIELD_DATE and FIELD_TIME, where I'd like to store the string representation of date & time, in a format depending on the Android user locale.
From what I've read, the android.text.format.DateFormat should help me. So I set:
java.text.DateFormat dateFormat = DateFormat.getMediumDateFormat(getActivity());
java.text.DateFormat timeFormat = DateFormat.getTimeFormat(getActivity());
Now I think I should call format(Date d) on both objects to get my string, but I don't know where do I get this Date object - don't even know if my two lines are correct. So:
How to get a string representation of current date & time, based on the user defined (at OS level) locale?
That said (asked), I wonder if two fields for date & time are really what I'm looking for. As said, at the end I would like to show a RecyclerView reading the database. In that I will also need to filter out entries based on date, i.e.
Entries referring to last week // last month // All
entries
So I'm also asking:
Is a two-text-fields pattern the right choice to store date & time, given the need to easily filter out entries belonging to, say, last week? Should I better have separate columns for day, month and year?
How to query the database to have only last week rows, given the FIELD_DATE / FIELD_TIME structure (or any other better structure you can suggest)?
I'm quite stuck on these three questions.
Edit: finally came up with how to get the strings I wanted at first, it was as simple as instantiating a new Date object:
Date d = new Date();
String date = DateFormat.getMediumDateFormat(getActivity()).format(d);
String time = DateFormat.getTimeFormat(getActivity()).format(d);
Now I have both the needs to display these strings (which is quite simple, as they are already formatted) and to apply some filter to the db, like entries belonging to last week (which, in turn, would be quite simple with current time in millis since 1970). What to do?
If you want to be able to run complex queries such as find all records from last week, I would recommend storing a timestamp in an integer instead. A timestamp is expressed as the number of milliseconds since the Epoch (Jan 1, 1970). It makes it easy to make queries on exact date and time ranges.
The timestamp is easily found from e.g. System.currentTimeMillis().
The other approach would be to use sqlite's built in date type, but I would personally choose the timestamp approach.
Is there any reason you would want to store it in the current locale's format in the first place? If you are displaying the date to the user you're likely better of formatting the timestamp into a date when displayed, using one of the many date features of Java and android such as java.util.Calendar, java.util.Date, android.text.SimpleDateFormat etc.
As an example, you could run this code to get the timestamp of the start of this month:
Calendar now = Calendar.getInstance();
now.set(Calendar.DAY_OF_MONTH, 1);
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
long startOfThisMonth = now.getTimeInMillis();

datetime('now') gives wrong time

The System-Time of my Android emulator is correct (currently 13:42). But when i use the datetime('now')-function to set the current time in my SQLite Database, the returned value is wrong (11:42).
Is there another time i need to set to get this working correctly?
The return value of datetime('now') is in UTC.
Try
datetime('now', 'localtime')
datetime('now') will return in GMT UTC - which you probably should do then handle the conversion to your local timezone in the app. If you keep it in UTC in the database, then convert it in your activities, your app will work correctly as the user moves around timezones

Categories

Resources