Using Dates in an MVC application - c#

I have coded a MVC 5 internet application and have a question in regards to international dates.
I am wishing to add a create date field to each of my objects when my objects are saved into a SQL database. As this application will be used internationally, what format should I use for the dates and do I need to use a specific UTC?
Thanks in advance

The most common .NET type is DateTime. A DateTime stores a date and optionally a time. It has a Kind property which determines if the value is one of three: local, UTC, or unspecified.
Another type is called DateTimeOffset. A DateTimeOffset stores a date and time relative to UTC. Additionally, it stores an offset from UTC as TimeSpan.
Console.WriteLine (DateTime.Now); // 1/28/2014 2:53:50 PM
Console.WriteLine (DateTimeOffset.Now); // 1/28/2014 2:53:50 PM -08:00
More Information : http://afana.me/post/aspnet-mvc-internationalization-date-time.aspx

Related

CRM 2011, Date in plugin and DST

I have one issue which I resolved by myself but yet need some confirming words whether I am 100% correct on my thought, just because there is not any documentation I found to prove myself correct.
My server is in DST time currently, CRM UI is also showing 1 hour up then data stored in db. that's fine.
When I calculate and store date with plugin, after my plugin update operation finishes, CRM platform deducts 1 hour from data I saved. I have read that when we do some operation via SDK related date time, CRM stores date time as it is. is it the case that when time is in DST, platform also get involves to deduct 1 hour by then ?
As a resolution, I have commented out my line of deducting 1 hour and letting CRM to do it now.
Am I correct on my understanding or it would be appreciable if some one can provide any documentation URL.
Any time you're working in the SDK, DateTimes are retrieved and stored as UTC. The CRM web platform will convert the UTC time into the user's time. You shouldn't need to be doing any Conversions of time, just using UTC.
Let's assume your local time is UTC -1 (with DST since UTC doesn't observe it). So if UTC is 14:00, your local time is 13:00.
Let's also assume your plugin in going to populate a date attribute on the entity that is for the current time, tomorrow. If your code looks like this:
entity.new_SomeDate = DateTime.Now.AddDays(1);
service.Update(entity);
Assuming DateTime.Now is 13:00, it'll store 13:00 in the database (as if it was UTC). Then when you go to look at the time value from the CRM website, since you're UTC - 1 it'll display 12:00, even though you wanted 13:00.
Now if your code looks like this:
entity.new_SomeDate = DateTime.UtcNow.AddDays(1);
service.Update(entity);
Assuming DateTime.Now is 13:00, it'll store 14:00 in the database since DateTime.UtcNow is 14:00. Then when you go to look at the time value from the CRM website, since you're UTC - 1 it'll display 13:00, since it'll take the UTC value - 1.
Now if your code looks like this:
entity.new_SomeDate = entity.new_UserEnteredDateFromCrm.AddDays(1);
service.Update(entity);
The new_UserEnteredDateFromCrm will already have been converted from the users' Time Zone to UTC and it'll work as expected.
This makes DateTimes that you would prefer to store as Dates very difficult though (birthdays anyone?) and you may have to think through it a little more in depth.
I've figured it out myself. that date has component in it which explores what kind of date time is it in. it can be either Utc, Local or Unspecified.
when you pass any date to CRM attribute via code. make sure that date time kind is Utc, otherwise CRM service internal operation will convert it to be into Utc.
In my case, I was stucked to this because when I read date from CRM, I had to set office start in that date. e.g. I needed to make 03/02/2014 12:00 to 03/02/2014 8:30 to make incoming date aligned with office start time. I was doing operation like,
DateTime InDate = Case.CreatedOn.Value;
DateTime Dt = new DateTime(InDate.Year,InDate.Month,InDate.Day,8,30,0)
Having InDate in Utc Time, I was creating new date object so it lost DateTime kind from Utc to Local ( having in DST it signifies to be 1 hour up)
to avoid, always set DateTime kind to be exactly as provided In date to new object. e.g. above operation can be done alternatively like.
DateTime InDate = Case.CreatedOn.Value;
DateTime Dt = new DateTime(InDate.Year,InDate.Month,InDate.Day,8,30,0)
Dt = DateTime.SpecifyKind(Dt,DateTimeKind.Utc)
Hope that Helps.

SharePoint DateTime default value respect timezone

I have a DateTime field (Date Only) that uses the "Today's Date" as a default value.
However, when a user adds an item to the list the date that is selected is respective to the GMT timezone.
Therfore if a user adds an item on 2/22/2012 at 7pm (EST) the default value will actually read 2/23/2012.
My first thought was to check the web application settings, and they were set to -5 EST. Then after some searching I found that time zones can differ based on a users regional settings. Testing this approach, I manually set a user to have a EST time zone, and performed the test that yielded the same result.
Finally, after more searching I found one article that said to use the Calculated Value portion of the DateTime field and specify "=NOW()"
This however returned "The formula contains a syntax error or is not supported."
Does anyone know of a way to have the default value of a DateTime field respect the time zone of the web application or the user?
Thank you.
Sharepoint stores all date field in UTC. That is, if you are saving a datetime field in a list, Sharepoint actually converts the time that you selected into UTC, and converts it back to whatever time zone the person is in when retrieving.
Begin by checking if there's a difference between your server timezone and your client. When using any API SharePoint will always return the UTC time and leave it up to you to make the conversion in your interface or application.
If you like to solve this differently you can't use the datetime datatype, instead store dates in text fields.
== UPDATE ==
If you got a date from SharePoint (always in UTC) and simply want to convert it to your local time this is a good practice
DateTime localDateTime = sharePointDate.ToLocalTime();
If you got the date as a string, or are uncertain of the formatting and whatnot this can be a good approach
string dateStr = ("2/18/2012 9:49:51 PM").ToString(CultureInfo.InvariantCulture);
DateTime convertedDate = DateTime.SpecifyKind(DateTime.Parse(dateStr), DateTimeKind.Utc);
DateTime localDateTime = convertedDate.ToLocalTime();
// Outputs 2/18/2012 10:49:51 PM since I'm +1 in sweden

How to store my dates?

I don't have much experience with Utc Dates, but from what I know, they are in most cases the best way to store dates.
But I'm currently working on a program and I'm in doubt what will be the best way to store my dates. In the program, a user can follow a course for five weeks, starting on the day of registration. Every day he has to fill in a form, which is saved for that day.
Currently, I'm saving the StartDate and EndDate of the course as DateTime (no Utc) Should I save this as Utc, or isn't it necessary? Because I only need the day (if the user registers on February 8th at 10:04, all the system needs to know is that February 8th is the first day of the course. Is there maybe a better way to store this information? And what would be the best way to save system-event-dates (like user logged in, account created, etc)?
I used to store the form-data also with a DateTime, to calculate on which day it was submitted, but I changed it so it only saves the relative day-number (e.g. day 5).
Btw, I'm using C# and a SQL Server database.
UTC (Coordinated Universal Time) has to do with the time component of a date. It's a standard way to store DateTimes so that you can compare without worrying about timezones.
If all you are worried about is the Date Component & Timezone/Location is unimportant you could just store it in the database as 2012-02-01 00:00:00
You can get the date only component in .NET using
System.DateTime.Today;
Alternatively if you're working with some other Date...
DateTime dt = DateTime.Now;
dt.Date; // <--- this will give the Date Component with the Time stripped back to 00:00:00
Why don't you just store the dates in a DATE database column, and not worry about time zones at all?
Generally you want to store in UTC if there is a functional requirement for your system to be able to work with users in different timezones.
Let's say you have a user in Hong Kong and a user in Sydney looking at the same event. If you want them both see the event date (and time) in their timezones, then here we are, you will probably need to store it in UTC and then present to users respecting their geo locations.
If you don't have such requirements, you don't do such conversions and you only assume one timezone then you don't need to add more complexity into your system, just use Date column and store the current date there.
But if you do - go for UTC. In this scenario you will need DateTime, not just Date. This is because 21:30 in one timezone can be 2:30 next day in another timezone so time really matters.
When showing to a user you may convert it to the user's timezone and then throw time away, but in order to make the conversion correct you will need to keep time.
It is easy to work with UTC in .NET, DateTime has .ToUniversalTime() method that converts a datetime value to UTC for you:
var utcNow = DateTime.Now.ToUniversalTime();
there is also a property:
var utcNow = DateTime.UtcNow;
EDITED
Use TimeZoneInfo static class to convert datetimes from/to timezones you need (for example from UTC to the specified user's timezone:
TimeZoneInfo.ConvertTimeToUtc(...)
TimeZoneInfo.ConvertTimeFromUtc(...)

C#/.NET Date: From local to UTC

I get date data from a user. That data is a date (e.g. 4/23/2011) and an hour (0 - 23), representing the time. This date/time that the user selects is a local time.
I need to convert this to a UTC DateTime. I have their GMTOffset for their location. How can I do this?
You should work with the DateTimeOffset structure, specifically, the constructor that takes the DateTime and the TimeSpan that represents the offset.
From there, conversions to/from UTC are a breeze, as the offset is embedded in the structure and not dependent on local system settings.
Note, even though not commonly adhered to, it is recommended to work with DateTimeOffset most of the time, as opposed to DateTime (see the note under the section titled "The DateTimeOffset Structure").
var utcDateTime =
new DateTimeOffset(userDateTime, TimeSpan.FromHours(userUtcOffset)).UtcDateTime;
Of course you can use TimeSpan differently if the GMT offset has minutes / fractions of an hour.
Just use the DateTime.ToUniversalTime in C#, will that do what you want?

In C#, convert Sql Server 2005 datetime value to another timezone

UPDATE
I am dealing with a legacy database where the datetime values have been stored in a specific timezone (not UTC). Assume it is not possible to change how we are storing these values.
END UPDATE
Say I have a SQL Server 2005 database with a table as follows:
[id] (int) not null
[create_date] (datetime) not null
Suppose my [create_date] has been stored, by convention, as timezone TZ-A.
Suppose I want to retrieve this value (using SqlClient) from the database and display it in another timezone, TZ-B.
How do I do this?
DateTime from_db = // retrieve datetime from database, in timezone TZ-A
DateTime to_display = //convert from_db to another timezone, TZ-B
Use TimeZoneInfo
TimeZoneInfo timeZone1 = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
TimeZoneInfo timeZone2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime to_display= TimeZoneInfo.ConvertTime(from_db, timeZone1, timeZone2);
I also agree that storing in UTC is the way to go. The only downside is trying to explain UTC to users who want to write their own reports.
Everyone has C# ways, I give you TSQL (sadly only 2008):
See below for doc, you probably want something like:
-- up here set the #time_zone variable.
SELECT
COl0, TODATETIMEOFFSET(COLDATE, #time_zone),.... ColN, from
Table_Original;
From MSDN
The SWITCHOFFSET function adjusts an
input DATETIMEOFFSET value to a
specified time zone, while preserving
the UTC value. The syntax is
SWITCHOFFSET(datetimeoffset_value,
time_zone). For example, the following
code adjusts the current system
datetimeoffset value to time zone GMT
+05:00:
SELECT
SWITCHOFFSET(SYSDATETIMEOFFSET(),
'-05:00');
So if the current system
datetimeoffset value is February 12,
2009 10:00:00.0000000 -08:00, this
code returns the value February 12,
2009 13:00:00.0000000 -05:00.
The TODATETIMEOFFSET function sets the
time zone offset of an input date and
time value. Its syntax is
TODATETIMEOFFSET(date_and_time_value,
time_zone).
This function is different from
SWITCHOFFSET in several ways. First,
it is not restricted to a
datetimeoffset value as input; rather
it accepts any date and time data
type. Second, it does not try to
adjust the time based on the time zone
difference between the source value
and the specified time zone but
instead simply returns the input date
and time value with the specified time
zone as a datetimeoffset value.
The main purpose of the
TODATETIMEOFFSET function is to
convert types that are not time zone
aware to DATETIMEOFFSET by the given
time zone offset. If the given date
and time value is a DATETIMEOFFSET,
the TODATETIMEOFFSET function changes
the DATETIMEOFFSET value based on the
same original local date and time
value plus the new given time zone
offset.
For example, the current system
datetimeoffset value is February 12,
2009 10:00:00.0000000 -08:00, and you
run the following code:
SELECT
TODATETIMEOFFSET(SYSDATETIMEOFFSET(),
'-05:00');
The value February 12, 2009
10:00:00.0000000 -05:00 is returned.
Remember that the SWITCHOFFSET
function returned February 12, 2009
13:00:00.0000000 -05:00 because it
adjusted the time based on the time
zone differences between the input
(-08:00) and the specified time zone
(-05:00).
As mentioned earlier, you can use the
TODATETIMEOFFSET function with any
date and time data type as input. For
example, the following code takes the
current system date and time value and
returns it as a datetimeoffset value
with a time zone -00:05:
SELECT TODATETIMEOFFSET(SYSDATETIME(),
'-05:00');
I'm not going to offer an answer, but rather a word of advice: Always store absolute dates in UTC, no matter what.
use the TimeZoneInfo class, it gives you built in time zone conversion functions using the Windows API.
http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx
Always store the data in the database as UTC. Then convert it in the client for display purposes from UTC to the local time using DateTime.ToLocalTime();
Check the method TimeZoneInfo.ConvertTime.

Categories

Resources