I have an entity with a DateTimeOffset (since .NET doesn't have a Date class) that is supposed to store a date (no time).
The problem is that, when I set the date to, for example, "2017-9-1" in the database it's saved as "2017-08-31 22:00:00+00" (2 hours less)
I think it applies the offset of my time zone to UTC.
I would like to store like to store "2017-9-1" in the database. The first thing I thought is to add 2 hours to every DateTimeOffet, but it feels bogus.
Is there a better way to work with dates than this?
I'm not quite sure, but add "0:" before the date on the format string, I think that should put it to your current time, otherwise it will default to UTC.
Like this:
[DisplayFormat(DataFormatString = "{0:yyyy/dd/MM}")]
If you are using MS Sql, you can use the Date variable to store just date. You can annotate the entities DateTimeOffset property database type.
[Column(TypeName="date")]
Related
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.
Is there something which I need to take into consideration when Im trying to serialize data into Mongo database which is keyed by DateTime?
My data looks like this SortedDictionary<DateTime, Data> Data and the problem Im facing is that the DateTime key have time part equal to 00:00:00 but after insertion into Mongo it is ISODate("2003-11-24T23:00:00Z") sometimes T22:00:00Z.
I preaty sure the problem is not with data Im inserting into DB I checked on every possible place if time part is always equal to 00:00:00 and it is.
mongo stores dates in UTC format by default so it seems you are in different time zone hence the difference
Are you converting from a string to a datatime in C#? Maybe that is causing it to be off by an hour because of daylight savings, local time, or UTC.
The C# mongodb driver handles the format. You could quickly test using something like an integer to be sure it's not your format prior to insertion. MongoDB DateTime Format
I'm battling with my model for storing dates in a web application used in different time zones. At the moment, all dates are stored in UTC dates. So, lets say I am allowing the user to save a Transaction date, and a field on the screen is "Transaction Date". I default it to DateTime.UTCNow. SQL Server is in the United States, and I am in Australia.
So, what I have done now, is when I present the default transaction date, I add the GMT Offset to the UTC Now date:
var usersCurrentDate = DateTime.UtcNow.AddSeconds(GmtOffset.Value);
Where GmtOffset is a value in seconds, difference from GMT.
This code works - the user get's presented with the current date/time in their zone.
My issue is - how I should store this. Going to the UI, I do the above conversion. Should I then have a converted on the way to the database that converts the date entered by the user, back into UTC date/time?
In that case, I am always sure that all dates in the database are UTC dates. And then when ever I get the data from the database, I need to remember to translate into Local time? So, have a function that takes a Local time (As entered by the user) and converts it to the UTC?
Something like:
public DateTime UserDateToUTC(DateTime userDate)
{
return DateTime.UtcNow.AddSeconds(GmtOffset.Value * -1);
}
Is this an acceptable pattern?
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.
I have created a smalldatetime field. I am using a dbml file to access that field. Can I either in the dbml file or the db cut the date part out of the datetime and only leave the time with out having to effect anything else (such as having to change types for example)
No. A datetime always has a date component. You would need to use the time datatype.
Before this existed a lot of people just use a date of 0 (1st January 1900) when they were only interested in storing times.
You have to option.
Create a partial class that contains an property that spits out only the part you want.
Create a varchar in the DB with only the part you want (a hack)