I'm going to add support of different timezone in my ASP.NET MVC3 app.
The solution is to store date values in UTC time, and store user timezone offset.
So, I need 2 things:
Send date values to user in "user time" (it's clear, I pass date to wrapper that convert time to user time)
Retrieve date from user in "user time" and convert it to UTC.
Question is - what is the nice way to convert all input date values to UTC time. Or is there a generic way to add some converting rules to ASP.NET MVC ?
This is ideal schema what I want (controller receive already converted values)
A way could be to create your own ModelBinder that do the work of mapping and preparing the data for your action method in the controller.
This post from Hanselman's Blog should give you an idea of what I mean. Obviously I'm assuming that you can get all the data you need inside the method
BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);
Like getting the user timezone with a repository or a hidden field in the post.
Related
So I have 2 types of dates in my db, date (yyyy-mm-dd) and datetimeoffset (yyyy-mm-ddThh:mm:ss.ms+Z), and I was wondering what is the best practice to deal with it when I'm taking the data from the DB and passing it as a json to the UI/mobile.
I used to always parse dates to datetimeoffset so normal dates will be something like 2018-09-24T00:00:00.000+00:00 instead of simply 2018-09-24 but it works perfectly with datetimeoffset that are already saved like that in the DB
In multiple ways you can handle this situation.
1 : From API side always give predefined date format value
Example yyyy-mm-ddThh:mm:ss.ms+Z
And from the client side based on conditions you can convert it.
2: Keep different View models/ Properties may be for storing yyyy-mm-dd you can give string data type and for yyyy-mm-ddThh:mm:ss.ms+Z just DateTime . and based on your db you can write a condition and map the particular data.
3: Keep a single property for returning the date and make it as string
Example : Public string CurrentDate{get;set;} and you can simply map the database values(Conversion should be done). In this case client no need to worry about the date conversions they can simply show what ever you are passing from the api.
Note : The method 3 is not preferable because in the case in some places the user may see yyyy-mm-dd in some other places yyyy-mm-ddThh:mm:ss.ms+Z.
Take a look at SQL Server Data Type Mappings
You will see that SQL Server's Date, DateTime and DateTime2 all map to .Net's DateTime data type,
and DateTimeOffset maps to DateTimeOffset.
SQL Server Database Engine type .NET Framework type
date (SQL Server 2008 and later) DateTime
datetime DateTime
datetime2 (SQL Server 2008 and later) DateTime
datetimeoffset (SQL Server 2008 and later) DateTimeOffset
I tried to use
sqlDr.GetValue(a).ToString()
to display a DATE column from my database which looks like this..(the Date Submitted column)
But the problem is , when i display it using getValue(8).toString(), something like this is displayed..
Thanks for taking your time to read my post , any reply is much appreciated!
The problem is .Net does not have a Date-only primitive type. Therefore the Sql Server Date column type maps to a full DateTime value in .Net, which always includes a time component. If you don't provide a time component, the DateTime struct will have a 0-value time component, which maps to 12:00:00.000 AM.
To get around this, you need to specify the output format for your column, so that it explicitly does not include a time value. You want something like this:
((DateTime)getValue(8)).ToString("d")
However, the exact code you need will vary wildly depending on how your result table is created. If necessary, check the SqlDataReader.GetDataTypeName() function to know what type you're dealing with.
Try using the DateTime.ToShortTimeString Method ():
Console.WriteLine("Short date string: \"{0}\"\n", myDateTime.ToShortDateString());
Output: Short date string: "5/16/2001"
In our Entity Framework app we are storing datetimes as UTC. The client uses a reflection utility to convert object graphs to their users timezone, and then back to utc when submitting changes to the server.
The utility works fine, but i'm considering a cleaner approach where I add a unmapped TimeZoneInfo property on the base class with a default value set to UTC, and then for each datetime property i would modify it like so:
private DateTime _endTime;
public DateTime EndTime
{
get
{
return _endTime.ConvertFromUtc(TimeZone);
}
set
{
_endTime = value.ConvertToUtc(TimeZone);
}
}
The idea is that the backing field is always stored as a UTC value. If the TimeZone proeprty is set to UTC, then the ConvertTo/From extension methods will not do any conversion and will simply return the backing fields value. Whereas, if the TimeZone is set to anything else then the conversion will take place, leaving the backing field in UTC.
What i'm wondering is if there are issues i'm not thinking of. For instance, I'm assuming it would serialize with a value based on the current TimeZone property...is that true? Also, would this work for code first entities in EF? My hope is that if the TimeZone is changed it would not trigger a change in the dbcontext. Are there any other considerations that i'm missing that would make this a bad idea, and what would a DDD implementator think?
Edit
To clarify the use case a little more, the service layer will retrieve the values from the db, serialize, and send it to the MVC Controller. The service layer does not know of the users timezone. In my mvc app the web controller cached the user timezone at logon. This controller will then use that value to set the TimeZone property on the object. It will then submit it to the client via JSON. The TimeZone property on the base class represents the current timzone of the object, not the users timezone. The values are always stored as UTC and the controller which sends the data to the client is responsible to make sure it is set to the correct timezone.
The biggest reason i am considering this is for business logic. The object in question is a schedule which has a start and end time. There are three requirements that would be easier to perform if the object were set to the users timezone. For instance, schedules cannot span weeks, so if it starts on Saturday (end of week) and ends on Sunday (start of week) it must be split into two different schedules. For some reason i have a more difficult time when working with datetime logic, and so anything i can do to simplify it is a plus for maintenance.
The thing is that your application's timezone will be the web server's timezone! If the user is visiting your site from another timezone, the conversion will be wrong.
You need to make your page determine via the browser what their timezone is and use that for conversions.
If you need the user's current time, you can use this:
Date.now()
// Or this if you need support for old browsers, like IE8
new Date().getTime()
That will give you UTC time in milliseconds since January 1st 1970. You will have to later convert that to C# time by doing this in your application:
DateTime date = new DateTime(valueFromJS * 10000 + 621355860000000000);
If you don't need the current time but a date+time entered by the user in a date picker, then you should create a date object in the browser from that and send the getTime() of that object. This way your web server always receives UTC time and it's up to the browser do the appropriate conversion.
You can also use new Date().getTimezoneOffset(), which will return the amount of minutes UTC is ahead of the user timezone. So if the user is in GMT -4, that function will return 240. If for some reason you need that in the web server, you can send that value from the browser. Alternatively, if your application has users, you can even store that as a setting and simply use that.
Now, to display the date in the browser's timezone, you have to either know beforehand the user's timezone (from a previous request or a user setting) or just send it in UTC and then convert that via JavaScript in the browser.
There are also useful libraries to deal with timezone problems. For example:
http://momentjs.com/timezone/
http://tzdata-javascript.org
I do not think my question was well worded, nor thought out. I decided to implement the above idea into part of my project and found that it just creates more confusion than it's worth. It's also adds too much risk, especially if used in objects that are persisted to the db, where a programmer may fail to convert the object back to utc.
Instead i am adding a much, much simpler way by adding an extension method to easily calculate based on a specified timezone. The extension method assumes the datetime object is in UTC:
public static DateTime? As(this DateTime? dt, TimeZoneInfo targetTimeZone)
{
if (dt.HasValue)
return dt.Value.As(targetTimeZone);
else
return dt;
}
public static DateTime As(this DateTime dt, TimeZoneInfo targetTimeZone)
{
return TimeZoneInfo.ConvertTimeFromUtc(dt, targetTimeZone);
}
This ensures the underlying object is not mutated unnecessarily.
In a web mvc5 application which supports en_Us and nb-NO cultures , How can i handle a Datetime object.
I have a ExpiryDate property in model .
How can i define the ExpDate property? What DisplayFormat i have to apply ? How can i convert that back in UI as per culture ? How can i save the data to SQlServer db as a valid datetime etc
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:DD.MM.YYYY}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> ExpDate { get; set; }
Does this helps [ which is not happening to me ]. Still confused on how to use the model in Controller and inside View while fecthing and saving data
Is any one knows some well written articles covering these aspects or any one can post some examples s\to solve this?
In general a good approach to handling these Globalization issues is to always save DateTimes as UTC on the database and also to work with UTC format at the business logic level.
In fact since you do not know until it is render time at UI which culture the user selected to see ( and not only the culture but also the time-zone ), better to stick and work with UTC values and also with a format independent approach, meaning that you should not convert the DateTime from/to string value ever anywhere else than to render in the UI or to get it from data entry form.
If you did not read anything else up to now, I would start with this article: Beginner's Tutorial on Globalization and Localization in ASP.NET MVC
or simply google by ASP.NET MVC Globalization.
good luck
One of the nastiest problems working across time zones :)
Here is my problem:
I have code that passes date into WCF via JSON object and I use "short" format where it contains only milliseconds since 1970 with no time zone. This DateTime parsed by WCF just FINE
I store date into SQL Server Database. Example: 2011-06-07 22:17:01.113 - date as I see it in SQL Server and this is perfectly fine since I store everything in UTC. So, it's (-5) time zone and date looks right.
I load date field into my object using EF and inside object property says it is 22:17 and Kind=Unspecified which is OK again, it is loaded from SQL, I know it is UTC but code doesn't know that so it loads this date as Unspecified.
I return this object to WCF client. It can be XML or it can be JSON. Here is what happen. When I JSON(this is what client specifies) - I get this: 1307503021113-0500 for date. If we convert first portion to DateTime using SQL:
SELECT DATEADD(ss, 1307503021,
'1970-01-01')
2011-06-08 03:17:01.000
Part above already wrong, no? If we apply -5hr adjustment we will be back to 22:17pm which already utc time? This part already confusing to me. But what even worse - when I deserialize using JavaScriptSerializer - I see DateTime value in newly inflated object saying UTC kind and 3:17am
var oSerializer = new JavaScriptSerializer();
var returnValue = (T)oSerializer.Deserialize(s, typeof(T));
I'm all puzzled already and I wonder if it's possible to force WCF and other serializer/deserializers to NOT do any time offsets and stuff? I'd rather format all dates for display manually and I want to store UTC dates in database.
UPDATE:
Looks like WCF thinks that if DateKind is Unspecified than it's LOCAL.
I did this: After I got objects from EF I specified Kind:
foreach (var tu in tripUpdates)
{
tu.DeviceTime = DateTime.SpecifyKind(tu.DeviceTime, DateTimeKind.Utc);
}
That fixed it - now when WCF serves object it doesn't include timezone which is GREAT. Now my main question is there any way to specify Kind on EF entities somehow so I don't have to manually specifiy kind for every date in service?
When you get the datetime via a SELECT statement always set the DateTime.Kind to UTC. This way WCF/XML will not try to adjust the time.