Read a DateTime object in a different time zone - c#

I have following scenario:
USA: database & application server
Europe: client
The server reads a date time (e.g. 12:00) object from the database and send it to a client in Europe. The problem is now, the client displays this date time in the time zone of the client (e.g. 18:00), but we need the time in the database, independent of the time zone of the server. On the client we don't know from which time zone this value is.
So how can we achieve this?

your tags tell the answer.
use the TimeZone Class.
http://msdn.microsoft.com/en-us/library/system.timezone.touniversaltime.aspx
also: Creating a DateTime in a specific Time Zone in c# fx 3.5
So in your DB, times should be UTC. from there you can do anything what you want.

Can't you simply use DateTime.ToUniversalTime()?
http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx
Alternatively, if you don't want UTC, you can find out the timezone of your server and do something like:
DateTime dt;
TimeZoneInfo timezone_EST =
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime dt_EST = TimeZoneInfo.ConvertTime(dt, timezone_EST);

If you're storing the DateTime data in SQL 2008, take a look at new datetimeoffset type which will store timezone information as well as the date and time themselves

Related

Convert from UTC C# SQL

Using a combination of server-side C#, SQL database, and the dayjs client-side library dayjs I am unable to convert the date stored as UTC in the database UTC to local time.
My theory is to store all date-times in the database as UTC. Use the client (browser) to determine the user timezone (automatically or store it for each user), then let the browser, via dayjs convert from UTC time to local time.
This is NOT a dayjs problem but the way dates are stored in SQL and pulled via C#.
In order for dayjs to convert the DateTime on the client app the date must be returned from the server in a very specific format.
If you are using DateTime C# and SQL datatypes and using just pulling the DateTime straight from the database to a DTO the date will be returned to the client like this:
noteDate: "2022-01-06T22:31:34.81"
In order for dayjs.tz() method to work the date DateTime must be returned from the server in this format:
noteDate: "2022-01-06T22:31:34.81Z"
Then this code will property convert from UTC to local time:
let date = "2022-01-06T20:14:18.917Z";
let timeZoneGuess = dayjs.tz.guess();
date = dayjs(date).tz(timeZoneGuess);
To get this format to the client I had to add additional information to the DateTime before returning the note.NoteDate to the client.
note.NoteDate = DateTime.SpecifyKind(note.NoteDate, DateTimeKind.Utc);
When storing the DateTime in SQL I am using c# DateTime and SQL DateTime datatypes. When setting the note.NoteDate I call note.NoteDate = DateTime.UtcNow but apparently SQL does not save the "Z" part of the UTC date.
I would like to see if anyone else has this same issue and if there are better ways to solve it.

Wrong date if date is wrong on computer using DateTime.UtcNow

I want to add posted date of product to database. I am using DateTime.UtcNow but it shows wrong date if date is wrong on computer. How can I solve this problem?
I have "prodpostDate" column in the "product" table and its type is nvarchar.
DateTime aDate = DateTime.UtcNow;
item.prodpostDate= aDate.ToString("dddd, dd MMMM yyyy");
_context.Products.Add(item);
The date is not wrong. The date is exactly what it should be. When you call Now functions, it pulls the date and time from the computer that executes the code. If the date is wrong on the computer, you need to update it/change the timezone.
Expanding on the comment below:
If you want the date and time regardless of a users local settings, you cannot get the date time from their local machine which is what happens if you call a Now function from code ran on the client. You need to make a call to a different source to get it. If you are using an API, you could make a call to it from your client to get the current date and time. Even better than that, if you end up sending a request to the server for an update, just don't send a date time and let the server get it and populate it. Or if you are doing a database update, let the database get the date time on update/insert.

getting datetime from different location

I need a time from different location. My server resides in the US but I need time from Australia.
when I save records in database, I use DateTime.Now() C# function. Is there a way I can get and save Australian time even though the server where my website is hosted is in US?
If there is any database solution then that will be ok too. I am using sql server
This is how you get your local time now:
DateTime yourLocalTime = DateTime.Now;
You can get current UTC time with DateTime.UtcNow or by converting local time to UTC time:
DateTime utcTime = DateTime.UtcNow;
DateTime utcTime = yourLocalTime.ToUniversalTime();
Save this time to database instead of saving some local time. How to get your local time from UTC time:
DateTime yourLocalTime = utcTime.ToLocalTime();
How to get time in other time zone:
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
DateTime tokyoLocalTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, timeZone);

Web application and UTC Dates

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?

Issue with dates in WCF service and in JavaSerializer decoder

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.

Categories

Resources