Datetime usually is define as datetime.
What if I want a column for just date and another column for time?
Can I define [date] or [time]?
Out of the box - no. While sql has datatypes date and time you can extend entity framework http://msdn.microsoft.com/en-us/library/vstudio/dd456844(v=vs.100).aspx with datatypes [Date] and [Time] or implement logic splitting DateTime in two values.
Related
I'm building an iOS app where I want to retrieve all the values from my database between two dates that the user picks. So for example, I want all the rows from the 1st of March to the 5th of March. Would look something like
SELECT * FROM MAIN WHERE DATE = '01/03/2020' AND ENDS ='05/03/2020'
So from that I would hope to retrieve all data from the 1st,2nd,3rd,4th and 5th of march. Any ideas on how to do this?
Thank you
Try to use comparison operators like:
DATE >= '01/03/2020' AND DATE <= '05/03/2020'
There are two issues:
Date types:
As Datatypes In SQLite Version 3 says:
2.2. Date and Time Datatype
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.
So storing dates in a dd/MM/yyyy format (using the DateFormatter capitalization convention) is problematic because in the absence of a native date type, it’s going to store them as strings, and therefore all comparisons will be done alphabetically, not chronologically, sorting values like 03/10/2009 (or nonsense strings like 02foobar, for that matter) in between the strings 01/05/2020 and 05/05/2020.
If, however you store them as yyyy-MM-dd, then it just so happens that alphabetical comparisons will yield chronologically correct comparisons, too.
SQL syntax:
Once you have your dates in your database in a format that is comparable, then if you have all of your dates in a single column, you can use the BETWEEN syntax. For example, let’s say you stored all of your dates in yyyy-MM-dd format, then you could do things like:
SELECT * FROM main WHERE date BETWEEN '2020-03-01' AND '2020-03-05';
But needless to say, you can’t use this pattern (or any comparison operators other than equality) as long as your dates are stored in dd/MM/yyyy format.
If you want to show all the data that has values of column "date" between this two dates then:
Select *
from MAIN
where `date` between '01.03.2020' and '05.03.2020';
If you want to show all the data that has values of column "ends" between this two dates then:
Select *
from MAIN
where ends between '01.03.2020' and '05.03.2020';
If you want to show all the data that has values of columns "date" and "ends" between this two dates then:
Select *
from MAIN
where ends between '01.03.2020' and '05.03.2020'
and `date` between '01.03.2020' and '05.03.2020';
Here is a demo
Let's say I want to represent a person with their name and date of birth. I could write this in Dart:
class Person {
String name;
DateTime dateOfBirth;
}
The problem is that DateTime has a timezone offset so if I want to sort people by age then I need to implement my own Comparator callback function which only looks at the year, month and day properties of dateOfBirth.
An alternative is to add a class invariant to Person to ensure that the dateOfBirth is always in UTC, then my sort comparator becomes much simpler: (p1, p2) => p1.dateOfBirth.compareTo(p2.dateOfBirth)
Both these approaches feel wrong because I don't care about the timezone component - what I really want is a class which just represents (year, month, day) in the Gregorian calendar. I've found this class, but it's not very popular. Is there some standard Dart class that I can use? Or do most Dart programmers just use DateTime to represent such a concept?
Just make sure only year/month/day are included when saving the DoB.
date = getDobFromUser();
dob = DateTime(date.year, date.month, date.day);
If you need more granularity than that, you should include the time they were born and probably store it as milliseconds since the Unix epoch for easy sorting.
I have a model where the data is stored in json format in a jsonb column in postgres.
I want to sort the output by a data field using an activerecord query.
Model.all.order("json_data -> 'date'")
gives me an output but orders it alphabetically based on the date string.
Is there an easy way I can sort this as a date?
Note: The dates are in the following format:
"Fri, 24 Jun 2016 04:13:26 -0700"
If the date is in a sensible format Postgres will deal with this automatically.
Model.all.order("(json_data ->> 'date')::timestamp with time zone DESC")
or
Model.all.order("(json_data ->> 'date')::timestamptz DESC")
If your date field string is a little unorthodox, you can do the following
Model.all.order("to_timestamp(json_data->>'date','Dy, DD Mon YYYY HH24:MI:SS ') DESC")
Details here
Note the ->> there to output the string rather than the json object.
You can of course just create an extra column and store your information there as per #Uzbekjon's answer below.
Is there an easy way I can sort this as a date?
Not as part of the jsonb field, since JSON doesn't know anything about dates.
So, an easy alternative would be to store them as a separate table column.
If you really have to store them as an element of your json field, then I would suggest one of the two options:
Store your field as timestamp. Since, json fields in postgresql support numeric values and it could (potentially) optimize the sorting.
Store your date in ISO 8601 format string. It would sort correctly, even if it is a string.
I am using Delphi 7, and Titan BTrieve to open a Pervasive Table.
It is a TtbTable component.
I am trying to apply the filter on a TimeStamp field with my code as follows:
Date:=InputDate;
DateString:=FormatDateTime('DD/MM/YYYY HH:NN:SS', InputDate);
Table1.Filter:='UPDATEDON > '+chr(39)+DAteString+chr(39);
Table1.Filtered:=True;
The problem is that the filter results are incorrect. It returns records that are before the do not match the filter criteria.
the Table1.Filter, filters the data in TDataSet not in btrieve/pervasive.
the problem is the date in string format... you must use the formar YYYY-MM-DD and not DD-MM-YYYY because the string compare.
in a string compare 17-06-2012 is grater than 16-07-2012, (17>16)
From the look of it, you are comparing strings, not dates.
What version of PSQL are you using? Is the UPDATEDON field defined as a Timestamp in the Btrieve database? If it's a timestamp, values are stored in 8-byte unsigned values representing septaseconds (10^-7 second) since January 1, 0001 in a Gregorian calendar, Coordinated Universal Time (UTC). It is not stored as a string.
Btrieve / PSQL stores dates in the 'YYYY-MM-DD' format.
WHat does a value from the UPDATEDON field look like? To use it as a filter, you need to make sure the filter value looks the same.
I am a parsing a file into a sqlite database that contains dates in the YYYY-MM-DD format. I want to store the entries into sqlite in such a way that I can sort the entries by date (strings not cutting it). What is the normal protocol for storing and ordering dates in sqlite? Should convert the dates into a number. Is there a way to convert YYYY-MM-DD dates into timestamps?
SQLite supports "DATE" in table creation. (More about that later.)
CREATE TABLE test (dt DATE PRIMARY KEY);
INSERT INTO "test" VALUES('2012-01-01');
INSERT INTO "test" VALUES('2012-01-02');
INSERT INTO "test" VALUES('2012-01-03');
SELECT dt FROM test ORDER BY dt;
2012-01-01
2012-01-02
2012-01-03
Values in the form yyyy-mm-dd sort correctly as either a string or a date. That's one reason yyyy-mm-dd is an international standard.
But SQLite doesn't use data types in the way most database workers expect it. Data storage is based on storage classes instead. For example, SQLite allows this.
INSERT INTO test VALUES ('Oh, bugger.');
SELECT * FROM test ORDER BY dt;
2012-01-01
2012-01-02
2012-01-03
Oh, bugger.
It also allows different date "formats" (actually, values) in a single column. Its behavior is quite unlike standard SQL engines.
INSERT INTO test VALUES ('01/02/2012');
SELECT * FROM test ORDER BY dt;
01/02/2012
2012-01-01
2012-01-02
2012-01-03
Oh, bugger.
You don't have to do anything special to store a timestamp in a date column. (Although I'd rather see you declare the column as timestamp, myself.)
INSERT INTO test VALUES ('2012-01-01 11:00:00');
SELECT * FROM test ORDER BY dt;
2012-01-01
2012-01-01 11:00:00
2012-01-02
2012-01-03
Oh, bugger.
SQLite will try to do the Right Thing as long as you feed consistent data into it. And it will sort dates correctly if you use the standard format.
Instead of storing date in format "YYYY-MM-DD", store the time-stamp of that date and that will help you to sorting the table.
If You want to Current TimeStamp then use
SELECT strftime('%s','now');
If You want toYYYY-MM-DD date TimeStamp then use
SELECT strftime('%s','YYYY-MM-DD');
where %s=seconds since 1970-01-01
i have the date field store in this way DD/MM/YYYY.
For sorting the date ( date field is a string ) i have to convert it before order it.
select (substr(date, 7, 4) || '-' || substr(date, 4, 2) || '-' || substr(date, 1, 2)) as new_date from work_hour order by new_date desc