Should I use DateTime UTC for an international application - datetime

I am coding a MVC 5 internet application that is being deployed to an Azure website. This application is going to be used internationally, and I am wanting to know if storing any DateTime values should use UTC time?
Here is an example: I have an object that has a start date time value as well as an end date time value. These values are set by a user and are used to determine if data should be shown to a user. If the current date time value is between the start date time and end date time, then data is shown.
Because my application is going to be used internationally, and there are different time zones, should I store the start date time value and end date time value as a DateTime object with UTC, or a standard DateTime value would be all that is needed? Do I need to worry about setting and displaying DateTime values for different time zones, or is this incorporated into the DateTime object?
Thanks in advance.
EDIT
How about when editing a DateTime that is stored as UTC.
If I have a DateTime that is stored as UTC in an object, and the user wants to change this value, do I need to convert the DateTime (that is displayed as .ToLocalTime()) back to a UTC DateTime when I store this value back in the database after it has been edited?
EDIT2
Can you have a quick look at these functions that I have coded to ensure the coding is correct?
public DateTime ConvertUTCDateTimeToLocalTime(DateTime utcDateTime)
{
DateTime convertedDate = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
return convertedDate.ToLocalTime();
}
public DateTime ConvertLocalDateTimeToUniversalTime(DateTime localDateTime)
{
DateTime convertedDate = DateTime.SpecifyKind(localDateTime, DateTimeKind.Local);
return convertedDate.ToUniversalTime();
}
public DateTime ConvertUTCDateTimeToLocalTime(string utcDateTime)
{
DateTime convertedDate = DateTime.SpecifyKind(DateTime.Parse(utcDateTime.ToString()), DateTimeKind.Utc);
return convertedDate.ToLocalTime();
}
public DateTime ConvertLocalDateTimeToUniversalTime(string localDateTime)
{
DateTime convertedDate = DateTime.SpecifyKind(DateTime.Parse(localDateTime.ToString()), DateTimeKind.Local);
return convertedDate.ToUniversalTime();
}

In general, you should prefer to use DateTime.UtcNow in your backend. First advantage is that you don't have to care about timezones and second, you don't have to do any calculations for Daylight Saving Times (read more in this article). .NET gives you great capabilities where you don't have to care much about the two points mentioned above. On the other side, you should never display the UTC time in your frontend. This can annoy your users, but here come the capabilities of .NET into play. If you have an UTC date you can easily convert it local time for displaying it to your user in the following way:
DateTime convertedDate = DateTime.SpecifyKind(
DateTime.Parse(dateStr),
DateTimeKind.Utc);
DateTime dt = convertedDate.ToLocalTime();
The snippet is taken from Drew Noakes answer on this thread, which is a great discussion about how you can convert your dates to local time.
EDIT
Regarding your edit: Yes, you have to do this. Otherwise the date will be stored in local time.

Related

CosmosDB converting DateTime properties to different timezone

I have already calculated UTC (the datetime is set to be equal to the current UTC time) for a datetime property on my entity. I write it to CosmosDB, and I see in the DataExplorer that Microsoft has changed the datetime, doing a time conversion that puts it into the ALMT (Almaty, Kazakhstan) timezone. Why?
Does anyone know of any settings that can be turned off to prevent this from happening?
As far as the TableEntity TimeStamp property, it is set to be +00:00, using my datetime property.
Once it has been written to CosmosDB, it's been changed all the way from 09:43 PM July 10th to 03:43 AM July 11th, or ALMT timezone.
Do this to your DateTime properties before writing them to CosmosDB, or it will convert them from whatever your local timezone (still not sure how exactly / based on what it infers that) to Utc (and if you've created the DateTime with DateTime.UtcNow, then the resulting datetime after CosmosDB converts it will be wrong):
DateTime UTCDateTime = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc);
After you set up your date time properties in your entity as such, no further date conversions will occur.

SQL find local date and time

I am facing the date and time issue in my sql server 2012 and web form. it is taking the server date and time. how i can get client location date and time. what i have done so far is.
Declare #TodayDate datetime
Set #TodayDate = (SELECT DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), GETDATE()))
it is giving me correct date only but not time. how to get both date and time.
In my webform i try this code, i got it from one forum again. Until now am not try it. Please help me to find correct solution for this.
DateTime convertedDate = DateTime.UtcNow;
DateTime localDate = convertedDate.ToLocalTime();
Actually it is not possible from server to locate user place. DateTime.Now show you server data not users date. You have to get user time through javascript. You can store utc time in Database. After that convert utc time to user time through javascript.

Convert to datetimeoffset from SQL query to local time based on TimeZoneInfo

For whatever silly reason, I remain confused when dealing with Timezones.
When a record is created, I use:
getutcdate()
So for example, it's stored in a datetimeoffset column and looks like this:
2015-07-03 20:44:21.0300000 +00:00
So no offset, just raw UTC.
Now, in server code, I want to do a few things... I have a query that gets me just the CreatedDate for articles posted for a particular user. I'm storing this in a datatable:
Dim tz as TimeZoneInfo = GetUserTZInfo(User)
Dim dt as DataTable = GetArticleDates(User)
Dim MaxArticles As Integer = 5
Dim PostedThisMonth As Integer
Dim Remaining As Integer
I'm limited the user to 5 articles posted per/month, so you can see where time can get shaky toward the beginning or end of the month based on the user's timezone. It's tomorrow somewhere, yet same moment in time everywhere.
But I want it to be user-friendly and just base it on the user, not server time.
I'm having difficulties using some of the examples on converting to local times because of my datatype of datetimeoffset
Could anyone suggest a best practice/method on how to achieve the following:
Search the dt for any created dates that are equal to the user's month.
Generate count for PostedThisMonth based on what's found.
The only sticky area like I said is at the beginning or end of the month... basically that 12 hour window, and then of course DST, but I'm less concerned with that.
Congratulations, you're ahead of most folks. You're doing it right by storing UTC times in your database and tracking the user's time zone with TimeZoneInfo.
If you never deviate from +00:00, you could store juse a datetime or datetime2 instead of a datetimeoffset, but it doesn't hurt anything and it has the added benefit of being unambiguously UTC.
All you really need to do is:
Use the user's time zone to convert the start and end of the user's local month to their equivalent UTC points in time.
Query your database using that range of values.
// compute the start of this month and the next month, by the user's time zone
Dim today As DateTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, tz).Date
Dim startDateOfThisMonth As DateTime = New DateTime(today.Year, today.Month, 1)
Dim startDateOfNextMonth As DateTime = startDateOfThisMonth.AddMonths(1)
// convert those to UTC
Dim startUtc As DateTime = TimeZoneInfo.ConvertTimeToUtc(startDateOfThisMonth, tz)
Dim endUtc As DateTime = TimeZoneInfo.ConvertTimeToUtc(startDateOfNextMonth, tz)
Or, since you're using datetimeoffset in your database, you could just build a DateTimeOffset in the last step. SQL will use the offset to convert to UTC internally when scanning the index.
Dim start As DateTimeOffset = New DateTimeOffset(startDateOfThisMonth,
tz.GetUtcOffset(startDateOfThisMonth))
Dim end As DateTimeOffset = New DateTimeOffset(startDateOfNextMonth,
tz.GetUtcOffset(startDateOfNextMonth))
When you query your database, use table.dto >= #start AND table.dto < #end (a half-open interval).

How to match client time with server time in datepicker control in asp.net

I have two text boxes each having date_picker control. In one text box the date with time is automatically populating while loading the page.That time its taking the server Date
-time.And in second text box a user have to select the date-time but it is taking system time.And it is mismatching.
I want while user select a date-time its automatically convert to server time.How is it possible ? Can anyone say me ?
Are you looking for the server's time but the user's selected date? If so, consider the following:
C#
DateTime ServerDateTime = new DateTime();
ServerDateTime = DateTime.Now;
DateTime ClientDate = clientDateControl.Value;
DateTime AdjustedDateTime = new DateTime(ClientDate.Year, ClientDate.Month, ClientDate.Day, ServerDateTime.Hour, ServerDateTime.Minute, ServerDateTime.Second);
VB
Dim ServerDateTime As DateTime = New DateTime()
ServerDateTime = DateTime.Now
Dim ClientDate As DateTime = clientDateControl.Value
Dim AdjustedDateTime As DateTime = New DateTime(ClientDate.Year, ClientDate.Month, ClientDate.Day, ServerDateTime.Hour, ServerDateTime.Minute, ServerDateTime.Second)
Using this, you can either continue using the second date picker control and substitute its value for the ServerDateTime variable or you can remove the second date picker control as you already know the server datetime serverside.
Can't say I fully understand what you are trying to accomplish, but generally speaking this is what we have UTC for.
UTC is the global baseline date and time. Using javascript or whatever server side language it should be very simple to convert both dates to UTC and compare them.
Best of luck.

DateTime Json Return From WebAPI with Default Serializer

I know this question has been hashed over multiple times and I read lots of posts on that hashing but still am confused.
Using MVC4/WebAPI, I have a datetime that is simply created as new DateTime.Now.
My WebAPI is return data like this:
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new
{
data = sessionRecordSmalls,
count = sessionRecordSmalls.Count,
success = true
});
where sessionRecordsSmall has a public property of DateTime in it.
When I look at the date in the VS debugger, it shows it as now with no timezone of course because DateTime does not include a timezone.
{10/6/2012 9:45:00 AM}
When I look at what gets downloaded from the server, I see in the JSON
2012-10-06T09:45:00
I think the T0 means Timezone 0, not 100% sure of that. My JavaScript library interprets it as timezone 0, then shows the actual date downloaded as GMT (-9 hours ago for me).
My question is, what is the JSON downloaded? Is that include a timezone? Am I missing some important step here?
if serializing with json.net keep in mind that you can specify DateTimeZoneHandling.
Example in WebApiConf.cs
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.DateTimeZoneHandling =Newtonsoft.Json.DateTimeZoneHandling.Local;
The date time 2012-10-06T09:45:00, which we recive in JSON with Web API and default serializer is the ISO 8601 format.
In fact this is so called Combined date and time representations. Extract:
..A single point in time can be represented by concatenating a
complete date expression, the letter T as a delimiter, and a valid
time expression. For example "2007-04-05T14:30"...
There is no time zone information in this format. As mentioned in the Time zone designators Extract:
Time zones in ISO 8601 are represented as local time (with the
location unspecified), as UTC, or as an offset from UTC. If no UTC
relation information is given with a time representation, the time is
assumed to be in local time.
In other words, if there is no offset from UTC specified, it is treated as a local time.
The UTC format would be extended with Z at the end
If the time is in UTC, add a Z directly after the time without a
space. Z is the zone designator for the zero UTC offset. "09:30 UTC"
is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would
be "14:45:15Z" or "144515Z".
UTC time is also known as 'Zulu' time, since 'Zulu' is the NATO phonetic alphabet word for 'Z'.
So, the date-time we recieve is the ISO 8601 format, treated as local time zone (no Z at the end like this 2012-10-06T09:45:00Z)

Resources