SQLITE datetime for different timzone required, not only localtime - sqlite

I want to fetch date and time, in different timezone using SQLITE. Say, I get the value as, 20160118T010856 in input, but I require it to change to Australian, England and other timezone.
What I am currently able to do is :
select datetime('2016-01-18T04:13:39','localtime');
Which only provides me for my current local time. Kindly help.

As far as I know this is not possible in sqlite. Your best bet is to store the datetime as UTC and do the conversion outside the database.
From the documentation you could apply an offset(modifier) to a date and time, but it doesn't take Daylight Savings Time into account.

Related

MSSQL and EntityFramework - Storing and reading utc datetime

I have a request to alter current columns which are type of 'time' and instead of capturing just time I need to capture so called "utc time".
My idea is to create a fixed codelist with all timezones, and then to reference it to a appropriate table as FK.
My questions are:
Can column of a type 'time' hold also an information regarding time zones (utc, for example 15:00:00 +2 (gmt + 2)) and if not, could you suggest me another type for that column?
Should I maybe need to separate it into two columns? For example: [15:00:00] - StartTime, [+2:00] - UtcOffset
EF Insert: When I do inserting to the db, for that particular column, should I convert my DateTime object to for example DateTimeOffset?
Thanks in advance.
From the comments in your question, it sounds like you are building an appointment scheduling system. I'll base my answer on that, because your specific questions aren't quite aligned to the scenario you described.
First, it's important to understand that the relationship between a time zone and an offset is a one-to-many relationship. One time zone can have multiple offsets. In other words, a time zone is not an offset, but rather a time zone has an offset.
A time zone represents a geographic region where the local time is the same throughout. It is identified by a string ID, such as "America/Los_Angeles" (an IANA time zone ID) or "Pacific Standard Time" (a Windows time zone ID). In .NET, you will use them on the TimeZoneInfo object with the Id instance property or methods like FindSystemTimeZonesById.
An offset is like -07:00 or +05:30 or even +13:45. Any given offset applies only at a particular date and time. For example, in America/Los_Angeles, either -08:00 or -07:00 apply depending on whether daylight saving time is in effect at a given point in time. Keep in mind that DST is not the only reason for offsets to be different - many time zones have changed their standard time at some point in their history.
Also, it's called an offset because it is deviated from UTC by a certain amount. UTC itself always has a zero offset, delineated either by +00:00 or sometimes by Z. It's similar to GMT, except in how it is defined. UTC applies universally, everywhere. GMT technically applies only on the prime meridian. They both refer to the zero offset. You should prefer to say "UTC" in most cases.
Next, you should separate your application logic between future scheduling and present/past record keeping.
Present/past is the easier of the two. Since the moment in time has actually occurred, the local time and its offset from UTC is fixed forever. You can either store the local time and its offset in a single .NET DateTimeOffset structure (mapped to a datetimeoffset field in SQL Server). In other words, you can simply store 2021-07-27T12:00:00-08:00.
Note that you could instead store the equivalent UTC date and time, which would be 2021-07-27T20:00:00+00:00. However you've then lost the local time, and thus would need to convert back using the original time zone if you wanted to see that time. Some people prefer that, but I think it's more useful to store the original value.
For future scheduling, the situation is a bit different. Consider that the offset might not be the same for one appointment as it will be for the next appointment in the same time zone. Also consider that the definitions for which offset apply might change in between the time you schedule the appointment and when it comes around. (The likelihood of that increases the further out you schedule.)
Thus, for each location you should not store an offset, but rather a time zone identifier. Add a TimeZoneId to your object that stores each location (or each appointment depending on your model schema). Use TimeZoneInfo.GetSystemTimeZones to list the available time zones. The DisplayName property can be shown to your user, and the selected Id property gets assigned to the TimeZoneId.
Next you have to consider if you are scheduling a single appointment or creating a recurring appointment pattern.
For a single appointment you simply need the local date and time for that appointment. You can use a .NET DateTime struct (use datetime2 in SQL). Don't apply an offset, and don't convert to UTC. Just store the information provided.
For recurring appointments, you need to think through the information provided and store exactly what is given. For example, if the appointment is at 10:00 every other Tuesday, you'll need to store "10:00", "Tuesdays" and "2 week intervals". The data types for each will vary depending on how you choose to store and apply them. For example, you might use a time type for 10:00, but you could store the other values using integers. Appointments of different patterns could get stored in different ways.
Alternatively, some like to store patterns using a string containing a CRON expression. You can google that for more details.
Now you have everything you need to both schedule an appointment and record that appointment after it happens. But there's one part missing - you'll likely want some table of upcoming appointments that are easily queryable. For that, you've got a few options:
You can create a separate table via a background job of some kind. Periodically it would query all the appointments, use their information to compute the next upcoming appointment time, and insert it. You can store that in a DateTimeOffset, either as local time or as UTC. (SQL Server will always compute indexes on the equivalent UTC time either way.)
You could just add another field to your appointments that shows the next actual appointment time. You can then compute the next upcoming appointment whenever the appointment is created or updated, or when that appointment occurs, and update the table accordingly.
With either approach keep in mind that you will want to periodically check for time zone data updates (either via Windows Update or keeping the tzdata package current on Linux). You will also want to periodically re-compute future appointment times, in case that time zone data has been modified in a way that affects the appointments.
If all of this sounds super complicated - sorry, but it is. Doing scheduling worldwide across time zones right is challenging. If you want it simpler, you might want to look into a pre-made solution such as Quartz.NET, which you can integrate into your application.

How to make timestamp the same between server and client in firebase?

I have a react app which uses firebase cloud functions. On the client side, I use pure javascript Date.now() to get the local time (PST timezone) of the client.
On server size, I also try to use the same approach to get the timestamp, but it is in different timezone. This will introduce an issue that if PST time is 8:15pm 12/07/2019, it will be 4:15am 12/08/2019, the date is different.
In this case, how can I keep the timestamp consistent between client and server side? Thanks!
There is no timezone data encoded into javascript Date objects or Firestore Timestamp object. Date objects represent time in terms of unix epoch time, which represents a specific point in time for all people on the planet. (Definitely learn what that is if you don't already.)
What you're likely doing is printing a string representation of the date, and it's being formatted the host's configured timezone. Since you haven't shown any code, it's impossible to say for sure, but it's a fact that Dates don't have a timezone.
If you want to format a date with a specific timezone, you should use a date formatting library that lets you specify which timezone should be represented in the string format.

Does SQL Server store DateTime Offset Agnostic?

I've been searching all morning and can't seem to get a handle on this (though I do have a few possible theories). It's also not impossible that this might be a duplicate but please take into account that all the questions I searched, didn't give a definitive answer but were rather too open to interpretation.
In SQL Server (>= 2012), a table column of type datetime, is it stored timezone offset agnostic or is how does it work? From my investigation, it would seem that datetimeoffset is the type that includes the offset with the date/time while datetime simply omits this?
When I read the data from the database, and use CONVERT( datetimeoffset, [My Column] ) it's giving me 2016-09-21 16:49:54.7170000 +00:00 while myself and the server are both in UTC +02:00 which reinforces my belief, am I correct?
What I'm trying to achieve, is allow data to be saved FROM various tz offsets (via a function), then saved into the database in UTC and finally convert the datetime value back to a (possibly different) offset. I don't care about DST / etc as the users browser will give me the current offset at the time of the saving and the viewing user will give me their tz offset at the time of viewing. For historic reports the exact time of day (DST dependent) is irrelevant.
Currently the database tables already use datetime as opposed to datetimeoffset; it's my observation that it's completely fine to continue with this, though at some point, it might be good to change to datetimeoffset in order to then have start recording the historic tz offset?
Any clarity will be greatly appreciated.
TL;DR; Yes. the DateTime (and DateTime2) data type is not time-zone aware.
The long version:
Official documentation of DateTime clearly states that the DateTime data type does not support time zone (nor daylight savings time). Same is true for DateTime2.
You can see in both pages there's a table that describes the data type's properties, and in that table, for both data types, the value for "Time zone offset aware and preservation" and for "Daylight saving aware" is "No".
Time zone offset aware and preservation No
Daylight saving aware No
The description of DateTime is as follows:
Defines a date that is combined with a time of day with fractional seconds that is based on a 24-hour clock.
The description of DateTime2 is as follows:
Defines a date that is combined with a time of day that is based on 24-hour clock.
datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.
The only data type that is timezone aware is DateTimeOffset:
Defines a date that is combined with a time of a day that has time zone awareness and is based on a 24-hour clock.
Btw, it is recommended to choose DateTime2 over DateTime, both by Microsoft official documentation:
Note
Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.
And by SQL Server professionals: Why You Should Never Use DATETIME Again!:
Datetime also have a bug/feature implicitly converting string literals of format yyyy-mm-dd / yyyy-mm-dd hh:mm:ss - Datetime will try to convert them using local settings, while Datetime2 will always convert them correctly.
Check out this SO post about it.

ASP.NET / SQL Server - Set Time Zone

We have an ASP.NET website and an SQL database hosted in US. Whenever I use the function Now() in VB.NET and getdate() in SQL, I get the US' current time. The problem is, the client is in the Philippines which is on GMT+8 Time Zone. My question is, is there any way I can set the Time Zone of a specific database and website so that when I use the functions, I'll get the Philippine's current time? How do you deal with this? As much as possible, we don't want to do subtraction or addition to the result date of the functions since in the future, clients will be from other country. It will give us headache updating the codes if we do that.
Thank you in advance!
Given that your clients may be in different time zones, you should store a timezone for the clients, that they (or you) can set as a preference for their account. Store all dates+times as UTC, and then convert to their timezone when displaying results in your interface.
This question has already been addressed to a great extent in the following question:
How to work with time zones in ASP.NET?
Follow-up:
Unfortunately, the SQL server date is a system-level setting, so it's not really something that can be manipulated on a per-session basis. It sounds like you will need to make some code changes, but you can isolate them.
Do you have a session-level variable which contains the client time zone offset? If not, create one.
Create a small date/time utility class.
In the utility class, provide 3 methods to:
(1) get the current date/time (offset to the client's time zone)
(2) pass in a database date/time to return the time offset for the client's TZ.
(3) pass in a time from the client to subtract out the client's TZ difference.
You will have to make code changes, but you can probably use those utility functions to wrap inputs and outputs everywhere, centralizing the logic. Microsoft has a page about mis-steps to avoid when using the DateTime class and manipulating time zones:
http://msdn.microsoft.com/en-us/library/ms973825.aspx#datetime_topic1a

SQL Server AutoDate

I have my server in US and my client is in India, the problem is when he is inserting data there is a autoDate inside MSSql Table, but as the server is in different time zone, We are getting date with 12Hours different, how to overcome it.
Date in Table is AutoDate GetDate()
Regards
Use of UTC format may solve your issue. Please refer to these links
Convert UTC/GMT time to local time
How to handle conversion of a DateTime independently of the timezone of the hosting server?
How about changing your default constraint and rely on GETUTCDATE() instead of GETDATE()? This would solve your issue from the storage perspective.
You'd have to slightly alter your html rendering as well, in order to generate the date in a user friendly format, taking into account the user's timezone.

Resources