TSQL Converting DateOffset to UTC - sql

I'm trying to convert the datetimeOffset stored in SQL Azure to UTC DateTime so that I can perform a proper calculation.
The DateTimeOffset is stored as local NewZealand Time as:
2011-05-31 21:40:00.0000000 +10:00
I need to convert the above values to UTC so that I can perform date time calculation. Is there any way to achieve this using TSQL and Azure SSRS?
Thanks heaps.

Here's another thread that may give you some ideas: TSQL: How to convert local time to UTC? (SQL Server 2008)
Off the top of my head, if you know the datetime you are working with is from New Zealand, you know what the UTC offset is. It should be based on one of two values (if they have daylight savings).
So do a dateadd with a function call that determines if you are in daylight savings or not. How do you determine if you are in daylight savings for a given date? Good question. Unless there is a .NET function you could turn into a CLR function, I would just create a look up table and a function that tests against that. The function either returns a boolean or the proper offset for New Zealand.
I would save the new derived value into a new column, but I'm not sure what your needs are.

Related

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())

Sql Server 2008 - Convert localized DateTime column to UTC

I have some columns in a few tables in my database that are all in the localized server DateTime values. I want to convert these all to UTC DateTime values (does not need to be DateTime2 since it will be assumed the new values will be in UTC).
I would like to do this in a single SQL statement. I am not entirely sure how to perform this as I do not spend a lot of time in the database.
Assumptions can be made that my table name is TestTable and my localized DateTime column is called TestDateTime.
I would want the script to do the update to the table as well as the conversion.
Any way to possibly do this?
You can substract getutcdate() from getdate() to find the difference:
select DateAdd(s,DateDiff(s, getdate(),getutcdate()), LocalizedDateColumn)
This assumes you are in the same summertime/wintertime state as the time you're trying to convert. Not ideal, but the best conversion I know of that you can do in pure SQL.
A C# client has a much stronger conversion:
yourDateTime.ToUniversalTime()
Unlike the SQL version, the .NET version will correctly convert a wintertime date during the summer.

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.

Store time of the day in SQL

How would you store a time or time range in SQL?
It won't be a datetime because it will just be let's say 4:30PM (not, January 3rd, 4:30pm).
Those would be weekly, or daily meetings.
The type of queries that I need are of course be for display, but also later will include complex queries such as avoiding conflicts in schedule.
I'd rather pick the best datatype for that now.
I'm using MS SQL Server Express 2005.
Thanks!
Nathan
Personally I would find this a reason to upgrade to 2008 which has a separate time datatype.
I would recommend still using a DateTime data type and ignoring the date values--ideally using the static MinDate for SQL (Google it). This will give you the benefits of working with a strongly typed field and the only cost will be a few extra bytes.
As for ranges, store them in two separate columns. Then you can subtract one from the other to determine the difference.
Edit: did some Googling.
SQL Server 2008 adds a Time data type, so you might want to consider that.
You can use SQL 2005's DateTime type and combine it with the CONVERT function to extract just the HH:MM:SS.MMM
SELECT CONVERT(VARCHAR(12), GETDATE(), 114) AS [HH:MI:SS(24H)] (Found on this handy-dandy page)
Different SQL versions support different minimum dates. You could use a static date that will be supported by all such as 1/1/2000, or you could use SQL 2005's minimum value of 1/1/1753 and append the time values to that startic day
So if you stick with 2005, pick your static date, like 1/1/2000, and store your times on it. So 1m:30s would be 2000-1-1 00:01:30.000, and 1h:15m would be 2000-1-1 01:15:00.000
You can then do Date2 - Date1 and get your result of (1h:15:m - 1m:30s) 2000-01-01 01:13:45.000. CONVERT it and you'll have 1:13:45.
You could store it as an int as 24 hour time and format as needed.
Or store it as a datetime with some fixed date and remove it as needed for display:
Jan 1 2000 4:30PM
I would go with datetime field as it gives you the power of all the datetime related functionality.
You might want to consider storing it as an int column representing the number of minutes since midnight. In your entity you could expose this as a TimeSpan (or int) representing the same thing. You'd only need to convert between your display values (time format) and the database value (minutes) in order to perform your queries and this could easily be done in your entity (TimeSpan.TotalMinutes, for example).
to me it sounds like you're developing a type of meeting scheduler or something to display the meetings.
i think that i would set it p with 2 columns MeetingStart and MeetingEnd, both as datetime fields. This way, you can determine the length of the meeting, and since you already have the date you can easily use it to display it on a calendar or something.

How to convert a SqlServer DateTime to universal time using SQL

I have a database with DateTime fields that are currently stored in local time. An upcoming project will require all these dates to be converted to universal time. Rather than writing a c# app to convert these times to universal time, I'd rather use available sqlserver/sql features to accurately convert these dates to universal time so I only need an update script. To be accurate, the conversion would need to account for Daylight savings time fluctuations, etc.
A User Defined Function would allow you to write an SQL query that looks like this:
SELECT toUTC([MyDateColumn], [MyTimeZoneColumn]) FROM [MyTable]
Then you get universal times back from the server without a lot of ugly syntax in the query itself. Now you could build the UDF for this with regular SQL similar to what Chris posted, but SQL Server 2005 and later will let you build the UDF using CLR (.Net: C# optional) instead. It has much better support for dates and can do a better job taking timezones and daylight savings time into account.
check out the convert function and the getutcdate function?
http://msdn.microsoft.com/en-us/library/ms187928.aspx
Check out this link from CodeProject.com - it does exactly what you want: take a date and a time zone, pass them to a UDF, and get the date in UTC or any other time zone.
IMPORTANT: Check the comments of that article - the author wasn't allowed to revise the article after a certain point, and there is an updated version of the code used for the UDFs in the comments that addresses some issues not found in the original article code.
ALSO IMPORTANT: Don't use this for querying large data sets. It's perfectly fine for a one-time load into a database, or for returning a UTC date for a single row (like a user login table or what have you.)
If you want performance, the only really acceptable method for time zone conversion is to have a lookup table that handles every possible time zone conversion for every single hour in a year, with a case statement to handle rollovers between years (ie December 31 - January 1 or vice versa.) Yes, the table is huge, but the query performance is nil.
SQL Doesn't have anything built in for this.
Two ways would be the C# application (you mentioned you don't want) or writing a really complicated update statement with something like:
UtcDate = DATEADD(hour, CASE WHEN OriginalDate BETWEEN x AND y THEN 4
WHEN OriginalDate BETWEEN x2 AND y2 THEN 5 ... END, OriginalDate)
Note - I'd recommend the C# app plus something like TZ4Net to handle the conversion.