How to standardize datetime format for all regions? - sql

Within my program i insert into the sql server the current time into a sql DateTime column.
Because the program is used by users around the world , i found out that some american users are receiving an error (which doesn't cause the program to crash) and i believe this is happening because of different date and time formats.
I use the following line of code to get the current time in a specific time zone but i understand that for different users i will get different time formats.
For example for american users i will get "MM-dd-yyyy" while for european users i will get "dd/MM/yyyy".
Dim CurrentTime As DateTime = System.TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("SOME LOCAL TIME ID"))
I've been trying to figure out how to standardize this format before inserting to the server without any luck.
Hopefully someone here may be able to help.
Thanks!

Presumably you're storing your DateTime values as UTC values (GetUTCDate() vs. GetDate()).
Ideally you'd be using datetime2 rather than datetime for your SQL field type, if you're using at least SQL Server 2008.
If you have a DateTime variable in the local time zone, you can convert it to UTC before storing it in SQL Server using DateTime.ToUniversalTime:
dim localDateTime as DateTime
dim storedDateTime as DateTime
localDateTime = DateTime.Now
storedDateTime = localDateTime.ToUniversalTime()
Also note the caveat about XP on that linked MSDN page.
When you retrieve the UTC value you can do the timezone adjustment to the local machine's timezone using DateTime.ToLocalTime():
Dim storedDateTime as DateTime
Dim localDateTime as string
storedDateTime = (DateTime)reader[Timestamp"]
localDateTime = myDateTime.ToLocalTime()
To get the correct format for the DateTime string, you should be able to use DateTime.ToString(). This will use the current culture for the thread:
Console.WriteLine(localDateTime.ToString())
You can override this manually if you like by specifying the culture:
Dim germanCultureInfo As New CultureInfo("de-DE")
Console.WriteLine(localDateTime.ToString(germanCultureInfo))

The displaying of dates is a UI problem. Converting from date to text and text to date should be done on the UI with the user current culture or forced through TryParseExact.
All of the business logic and database should not depend on the user culture or timezone. In your case, it would be ideal to have everything stored as UTC.
If you start storing the hour, you'll quickly see how messy it'll get with each country having different DLS.

Related

Format DateTime without converting to String in SQL Server?

I have a view in SQL Server 2012 and there is a column of containing dates&times. I have been trying to convert the date column as '20/10/2018 18:00' format (no second) by using this feature and lots of approaches on Stackoverflow and other web sites:
FORMAT(StartDate, 'dd.mm.yyyy hh:mm')
However, as the data type of this column is Varchar (String) rather than DateTime, I encountered some problems in C# side and I want to perform this conversion on the database side without changing the data type of the generated format). Is there any way to achieve this?
SQL Server doesn't have a "date format" per se. The formatting of datetime fields is only performed when presenting the datetime to an output - that is, when converting it to a string.
There is a default format for presentation that is controlled by the server's collation setting. However, internally the date is stored as a numeric value (actual format varies by type, as datetime and datetime2 have different internal formats), and that value has no associated formatting.
You can store your date without seconds by using a smalldatetime field, or by manipulating the input data to trim off the seconds value. But, unless you store your date as a string, which is absolutely not recommended, you will not be able to save an output format different from the default collation-driven format in a datetime field.
I would migrate that column to a datetime (or some variant) if possible. Alternatively if that would affect too many things, you could make a computed column on the table which converts the string date you have to a datetime. That way the database doesn't have to care about the formatting at all; it just works with the proper DateTime data type.
If neither of those is an option, you can just pas the string to C# and use DateTime.TryParse() to convert it to a C# DateTime object.
In either case, it's preferable to work with the date as a DateTime up until the very last minute where you need to format it for display somewhere.

use Datetime to do a query in SQL database

I need to retrieve a tuple from the database that have a DateTime as a primary key, the problem i'm having is that it's only working with Datetime's that have the time before midday, otherside it fails to retrieve anything, here is the code:
string fecha = "22-11-2016 15:56:50";
DateTime myDate = DateTime.ParseExact(fecha, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
modelo.solicitud = BD.Solicitud.Find(myDate);
in resume I get a null in modelo.solicitud
if the string fecha is like "01-01-2017 09:00:00" (before midday) it success to retrieve from database, but if it's like "01-01-2017 16:00:30" will fail to retrieve a thing..
Any help of recomendation will be appreciated..
Regardless of the DBMS you are using, fields (columns) that are defined as DATETIME are stored as a binary value. What you see is a generated string representation of the binary value according to either the defaults defined for the DB or a specific format you define for presentation.
You can try setting the default datetime format to something like 'yyyy-mm-dd hh24:mm:ss' (hh24 is Oracle's way to say that you want the hours part to be in the 0-23 range; you will need to check how this is done in your case).
This format also removes ambiguities related to the American/European way of writing dates (i.e. mm/dd/yyyy in the US vs. mm/dd/yyyy in Europe, such that 3/4/16 would mean March the 4th 2016 in the US but April the 3rd 2016 in Europe).
Last, the Spanish word resume has a different meaning than in English (you would normally say summary).
Hope this is clear for you now.

How can I store date only in datetime field in WebMatrix with Sql Server CE?

I was wondering if there was a way to store a date (example: 01/01/2013) as datetime without SQL Server CE adding the time (example: 12:00:00 AM).
I could always store it as the string "01/01/2013" but I really want to be able to compare the dates on querying the database.
I realize that as long as I only stored the date part, all of the times in the datetime field would have equal values (i.e. 12:00:00 AM), so comparing them wouldn't be a problem and I could just always ignore the time part, however, it seems ridiculous to have this unnecessary data appended to every entry in the table.
Is there a way to store only the date part of the datetime as datetime so that the dates can still be compared in the SQL query or do I just need to live with this overhead and move on?
Side Note:
I just spent the last 30 minutes searching Google and SO for an answer I was sure was already out there, but to my surprise, I couldn't find anything on this issue.
Update:
The conclusion I have come to is that I will just accept the time in the datetime format and let it always default to 12:00:00 AM by only adding the date part during the INSERT statement (e.g. 01/01/2013). As long as the time part always remains the same throughout, the dates will still be easily comparable and I can just trim it up when I convert it to string for screen display. I believe this will be the easiest way to handle this scenario. After all, I decided to use SQL for the power of its queries, otherwise, I might have just used XML instead of a database, in the first place.
No you really can't get rid of the time component. It is part of the data type defined by sql server. I was very annoyed by it until I found that I could still display the dates without the time using JQuery to reformat them with the date formatter plugi:
https://github.com/phstc/jquery-dateFormat
Good Luck!
select CONVERT(date, GETDATE())

Access SQL Date Format

How can I retrieve a record based on a Date property? I'm trying:
WHERE Meetings.[MDate] = '16/12/2011'
which is the format I use but I get :
"Data type mismatch in criteria expression"
Problem solved: It should have been:
WHERE Meetings.[MDate] = 16/12/2011
No quotation marks.
For where clauses use
columnName = #mm/dd/yyyy#
You'll want to use the SQL date format: '#2011-12-16#'
Use the cast to DATETIME function, CDATE(), which will honour the machine's regional settings. That said, it still a good idea to use an unambiguous date format and the ISO 8601 format is a good one.
Also note that Access doesn't have a date data type: its sole temporal data type is DATETIME and, as its name suggests, always has a time element accurate to one second time granule, even if that time happens to be midnight. Therefore, it is a good idea to always include a time value to one second time granule in all DATETIME literals e.g.
WHERE Meetings.MDate = CDATE('2011-12-16 00:00:00');
Another advantage to the above is that the Access UI will not attempt to reformat the DATETIME literal because it is held as a string.

SQLite and inserting the current date in UTC format

How do I use an SQL statement on an sqllite database to insert the current date in UTC. I found the NOW function but what format is that in? This will be on mobile devices so everyone will have a different locale, however, I need a standard time format because the device will compare the dates with my server.
Also, is there a way to automatically update a 'modified' field when the data in the row is changed like you can in MySQL?
SELECT DATETIME('now') returns the current UTC datetime. See Date And Time Functions. You can use DATETIME DEFAULT CURRENT_TIMESTAMP with column declaration.
Format 11, the string 'now', is
converted into the current date and
time as obtained from the xCurrentTime
method of the sqlite3_vfs object in
use. Universal Coordinated Time (UTC)
is used
For the 'modified' field you can use a trigger.
You don't specify what you use to develop your application on. I prefer using QDate::toJulianDay and QDate::fromJulianDay in Qt to store dates in an SQLite database as an integer if I only need to store the date.