How to convert the format of inserted datetime in Informix? - datetime

I insert my date/time data into a CHAR column in the format: '6/4/2015 2:08:00 PM'.
I want that this should get automatically converted to format:
'2015-06-04 14:08:00' so that it can be used in a query because the format of DATETIME is YYYY-MM-DD hh:mm:ss.fffff.
How to convert it?

Given that you've stored the data in a string format (CHAR or VARCHAR), you have to decide how to make it work as a DATETIME YEAR TO SECOND value. For computational efficiency, and for storage efficiency, it would be better to store the value as a DATETIME YEAR TO SECOND value, converting it on input and (if necessary) reconverting on output. However, if you will frequently display the value without doing computations (including comparisons or sorting) it, then maybe a rococo locale-dependent string notation is OK.
The key function for converting the string to a DATETIME value is TO_DATE. You also need to look at the TO_CHAR function because that documents the format codes that you need to use, and because you'll use that to convert a DATETIME value to your original format.
Assuming the column name is time_string, then you need to use:
TO_DATE(time_string, '%m/%d/%Y %I:%M %x') -- What goes in place of x?
to convert to a DATETIME YEAR TO SECOND — or maybe DATETIME YEAR TO MINUTE — value (which will be further manipulated as if by EXTEND as necessary).
I would personally almost certainly convert the database column to DATETIME YEAR TO SECOND and, when necessary, convert to the string format on output with TO_CHAR. The column name would now be time_value (for sake of concreteness):
TO_CHAR(time_value, '%m/%d/%Y %I:%M %x') -- What goes in place of x?
The manual pages referenced do not immediately lead to a complete specification of the format strings. I think a relevant reference is GL_DATETIME environment variable, but finding that requires more knowledge of the arcana of the Informix product set than is desirable (it is not the first thing that should spring to anyone's mind — not even mine!). If that's correct (it probably is), then one of %p and %r should be used in place of %x in my examples. I have to get Informix (re)configured on my machine to be able to test it.

Related

How can I convert timestamps to dates in SQLite?

How can I convert timestamps to dates in SQLite?
The following code only produces a Timestamp column and a Date columns with NULL values. The the SQL code needs to convert from a "08/28/2020 8:00" format.
SQL CODE:
'''Select Timestamp, strftime('%m-%d-%Y', Timestamp) as Date
FROM Room_Data'''
The SQLite documentation is pretty clear, but I can't seem to get the desired result.
The strftime is meant to format a date, rather than perform conversion.
In the meantime you could try something like that to gather the pieces:
SELECT Timestamp,
SUBSTR(c,7,4) || '-' || SUBSTR(Timestamp,1,2) || '-' || SUBSTR(Timestamp,4,2) as Date
FROM Room_Data
Since SQlite doesn't really have the concept of a date, unlike other DBMS, the best choice would be to convert your dates to integer, either as Unix timestamps or in string form (YYYY-MM-DD) but storing dates as integer like 20201010 would be acceptable too.
NB: be careful with names like Timestamp or Date, they are reserved keywords in many programming languages and DBMSes.
The original code won't work in Windows 10 for some reason. Trying this from a Linux distro (Kubuntu, in this case) seems to resolve the issue. In Windows, the date needs to be converted to a '2020-01-01' format to actually work.
SQLite is amazing, but not sure why functionality changes for Windows 10. Feel free to comment if you know more about the differences.

SQLite date split

In SQLite, I have a 'date' field that's varchar(20), as an example dates currently read '12-AUG-15'. I need to split the date field into 4 separate fields: 'day', 'month', 'year', and 'month_num'. Problem is I don't know how to convert month names into numbers as well as the year into a 4 digit year. I'm thinking of using case and string concatenation functions? Any advice how to start it is well appreciated.
SQLite has very limited date and string functions. The date functions understand ISO 8601. You're better off in the long run converting to ISO 8601 and then using the date functions. It will sort better, and most everything understands ISO 8601 format.
SQLite doesn't have an easy way to do this, but you can write a user defined function to do the conversion. Most SQLite drivers allow you to write it in whatever language you're using. Here's an example in Ruby.
require "sqlite3"
require "date"
# Open a database
db = SQLite3::Database.new "test.db"
# Create a SQLite function date_to_iso()
db.create_function( "date_to_iso", 1 ) do |proxy, date|
# Convert 12-AUG-15 to 2015-08-12 (ISO 8601 format)
iso = Date.strptime(date, "%d-%b-%y");
# This is how you return the result via a FunctionProxy
proxy.result = iso.to_s
end
# Now you can use date_iso_iso() in SQLite queries in this process.
db.execute("UPDATE stuff SET date = date_to_iso(date)")
Then you can use strftime to query the individual date parts.
select
strftime("%d", date) as day,
strftime("%m", month) as month,
strftime("%Y", year) as year
from whatever;
Unfortunately, SQLite doesn't have a way to convert to the month name. You could write a big CASE statement.
select case strftime("%m", month)
when 1 then 'JAN'
when 2 then 'FEB'
...
end
from whatever;
Or you could add another user defined function to do the conversion.
But since you now have a standard date format, it's probably better to just return the whole ISO 8601 date and let the application do what it wants with it.

SQLite less than operator problem

I am using SQLite for a project and < symbol is not working in the query.
There is a table named Holidays which has a field of datatype datetime.
Suppose the table contains some dates of current year in the column HolidayDate.
SELECT HolidayDate
FROM Holidays
WHERE (HolidayDate >= '1/1/2011')
AND (HolidayDate <= '1/1/2012')
The < symbol in the above query is not working. > symbol in the above query is working well.
Please help me.
Try:
SELECT HolidayDate
FROM Holidays
WHERE HolidayDate >= date('2011-01-01')
AND HolidayDate <= date('2012-01-01')
(date format must be YYYY-MM-DD)
There is no datetime datatype in sqlite.
Sqlite only has 4 types:
integeral number
floating-point number
string (stored either as utf-8 or utf-16 and automatically converted)
blob
Moreover, sqlite is manifest-typed, which means any column can hold value of any type. The declared type is used for two things only:
inserted values are converted to the specified type if they seem to be convertible (and it does not seem to apply to values bound with sqlite_bind_* methods at all)
it hints the indexer or optimizer somehow (I just know it has trouble using indices when the column is not typed)
Even worse, sqlite will silently accept anything as type. It will interpret it as integeral type if it starts with "int", as string if it contains "char" or "text", as floating-point number if it is "real", "double" or "number" and as blob if it's "blob". In other cases the column is simply untyped, which poses no problem to sqlite given how little the typing means.
That means '1/1/2011' is simply a string and neither dates in format 'mm/dd/yyyy' nor dates in format 'dd/mm/yyyy' sort by date when sorted asciibetically (unicodebetically really).
If you stored the dates in ISO format ('yyyy-mm-dd'), the asciibetical sort would be compatible with date sort and you would have no problem.

SELECT clause with a DATETIME column in Sybase 15

I'm trying to do a query like this on a table with a DATETIME column.
SELECT * FROM table WHERE the_date =
2011-03-06T15:53:34.890-05:00
I have the following as an string input from an external source:
2011-03-06T15:53:34.890-05:00
I need to perform a query on my database table and extract the row which contains this same date. In my database it gets stored as a DATETIME and looks like the following:
2011-03-06 15:53:34.89
I can probably manipulate the outside input slightly ( like strip off the -5:00 ). But I can't figure out how to do a simple select with the datetime column.
I found the convert function, and style 123 seems to match my needs but I can't get it to work. Here is the link to reference about style 123
http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.blocks/html/blocks/blocks125.htm
I think that convert's slightly wrongly documented in that version of the docs.
Because this format always has century I think you only need use 23. Normally the 100 range for convert adds the century to the year format.
That format only goes down to seconds what's more.
If you want more you'll need to past together 2 x converts. That is, past a ymd part onto a convert(varchar, datetime-column, 14) and compare with your trimmed string. milliseconds comparison is likely to be a problem depending on where you got your big time string though because the Sybase binary stored form has a granularity of 300ms I think, so if your source string is from somewhere else it's not likely to compare. In other words - strip the milliseconds and compare as strings.
So maybe:
SELECT * FROM table WHERE convert(varchar,the_date,23) =
'2011-03-06T15:53:34'
But the convert on the column would prevent the use of an index, if that's a problem.
If you compare as datetimes then the convert is on the rhs - but you have to know what your milliseconds are in the_date. Then an index can be used.

How to convert date to mm/dd/yyyy format

I want to convert dateformat to mm/dd/yyyy. Whatever dateformat is coming in textbox, I want to convert it into mm/dd/yyyy.
First you need to get it into a datetime object. The most common standards work via:
DateTime x = DateTime.Parse(txtDate.Text);
If you expect a freaky format, you still have to know what format it is:
DateTime x;
DateTime.TryParseExact(txtDate.Text, "YYddd", out x);
Then simply output the data:
string date = x.ToString("MM/dd/yyyy");
But you really need to enforce your formatting using regex, validators, scout's honor - something.
see MSDN for full details.
You will need to parse the input to a DateTime object and then convert it to any text format you want.
If you are unsure what format you may be getting, maybe it is a good idea to restrict the user to a single format (using validation or better yet a date picker).

Resources