I am building an application in MVC3 and when a user comes into my site I want to know that user's timezone. I want to know how to do this in c# not in javaScript?
As has been mentioned, you need your client to tell your ASP.Net server details about which timezone they're in.
Here's an example.
I have an Angular controller, which loads a list of records from my SQL Server database in JSON format. The problem is, the DateTime values in these records are in the UTC timezone, and I want to show the user the date/times in their local timezone.
I determine the user's timezone (in minutes) using the JavaScript "getTimezoneOffset()" function, then append this value to the URL of the JSON service I'm trying to call:
$scope.loadSomeDatabaseRecords = function () {
var d = new Date()
var timezoneOffset = d.getTimezoneOffset();
return $http({
url: '/JSON/LoadSomeJSONRecords.aspx?timezoneOffset=' + timezoneOffset,
method: 'GET',
async: true,
cache: false,
headers: { 'Accept': 'application/json', 'Pragma': 'no-cache' }
}).success(function (data) {
$scope.listScheduleLog = data.Results;
});
}
In my ASP.Net code, I extract the timezoneOffset parameter...
int timezoneOffset = 0;
string timezoneStr = Request["timezoneOffset"];
if (!string.IsNullOrEmpty(timezoneStr))
int.TryParse(timezoneStr, out timezoneOffset);
LoadDatabaseRecords(timezoneOffset);
... and pass it to my function which loads the records from the database.
It's a bit messy as I want to call my C# FromUTCData function on each record from the database, but LINQ to SQL can't combine raw SQL with C# functions.
The solution is to read in the records first, then iterate through them, applying the timezone offset to the DateTime fields in each record.
public var LoadDatabaseRecords(int timezoneOffset)
{
MyDatabaseDataContext dc = new MyDatabaseDataContext();
List<MyDatabaseRecords> ListOfRecords = dc.MyDatabaseRecords.ToList();
var results = (from OneRecord in ListOfRecords
select new
{
ID = OneRecord.Log_ID,
Message = OneRecord.Log_Message,
StartTime = FromUTCData(OneRecord.Log_Start_Time, timezoneOffset),
EndTime = FromUTCData(OneRecord.Log_End_Time, timezoneOffset)
}).ToList();
return results;
}
public static DateTime? FromUTCData(DateTime? dt, int timezoneOffset)
{
// Convert a DateTime (which might be null) from UTC timezone
// into the user's timezone.
if (dt == null)
return null;
DateTime newDate = dt.Value - new TimeSpan(timezoneOffset / 60, timezoneOffset % 60, 0);
return newDate;
}
It works nicely though, and this code is really useful when writing a web service to display date/times to users in different parts of the world.
Right now, I'm writing this article at 11am Zurich time, but if you were reading it in Los Angeles, you'd see that I edited it at 2am (your local time). Using code like this, you can get your webpages to show date times that make sense to international users of your website.
Phew.
Hope this helps.
This isn't possible server side unless you assume it via the users ip address or get the user to set it in some form of a profile. You could get the clients time via javascript.
See here for the javacript solution: Getting the client's timezone in JavaScript
You will need to use both client-side and server-side technologies.
On the client side:
(pick one)
This works in most modern browsers:
Intl.DateTimeFormat().resolvedOptions().timeZone
There is also jsTimeZoneDetect's jstz.determine(), or Moment-Timezone's moment.tz.guess() function for older browsers, thought these libraries are generally only used in older applications.
The result from either will be an IANA time zone identifier, such as America/New_York. Send that result to the server by any means you like.
On the server side:
(pick one)
Using TimeZoneInfo (on. NET 6+ on any OS, or older on non-Windows systems only):
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("America/New_York");
Using TimeZoneConverter (on any OS):
TimeZoneInfo tzi = TZConvert.GetTimeZoneInfo("America/New_York");
Using NodaTime (on any OS):
DateTimeZone tz = DateTimeZoneProviders.Tzdb["America/New_York"];
I got the same issue , Unfortunately there is no way for the server to know the client timezone .
If you want you can send client timezone as header while making ajax call .
In-case if you want more info on adding the header this post may help how to add header to request : How can I add a custom HTTP header to ajax request with js or jQuery?
new Date().getTimezoneOffset();//gets the timezone offset
If you don't want to add header every time , you can think of setting a cookie since cookie is sent with all httpRequest you can process the cookie to get client timezone on server side . But i don't prefer adding cookies , for the same reason they sent with all http requests.
Thanks.
For Dot Net version 3.5 and higher you can use :
TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
but for Dot Net lower than version 3.5 you can handle it manually via this way :
first, get Offset from the client and store it in the cookie
function setTimezoneCookie(){
var timezone_cookie = "timezoneoffset";
// if the timezone cookie does not exist create one.
if (!$.cookie(timezone_cookie)) {
// check if the browser supports cookie
var test_cookie = 'test cookie';
$.cookie(test_cookie, true);
// browser supports cookie
if ($.cookie(test_cookie)) {
// delete the test cookie
$.cookie(test_cookie, null);
// create a new cookie
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
// re-load the page
location.reload();
}
}
// if the current timezone and the one stored in cookie are different
// then store the new timezone in the cookie and refresh the page.
else {
var storedOffset = parseInt($.cookie(timezone_cookie));
var currentOffset = new Date().getTimezoneOffset();
// user may have changed the timezone
if (storedOffset !== currentOffset) {
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
location.reload();
}
}
}
after that you can use a cookie in backend code like that :
public static string ToClientTime(this DateTime dt)
{
// read the value from session
var timeOffSet = HttpContext.Current.Session["timezoneoffset"];
if (timeOffSet != null)
{
var offset = int.Parse(timeOffSet.ToString());
dt = dt.AddMinutes(-1 * offset);
return dt.ToString();
}
// if there is no offset in session return the datetime in server timezone
return dt.ToLocalTime().ToString();
}
I know the user asked about a non-javascript solution, but I wanted to post a javascript solution that I came up with. I found some js libraries (jsTimezoneDetect, momentjs), but their output was an IANA code, which didn't seem to help me with getting a TimeZoneInfo object in C#. I borrowed ideas from jsTimezoneDetect. In javascript, I get the BaseUtcOffset and the first day of DST and send to server. The server then converts this to a TimeZoneInfo object.
Right now I don't care if the client Time Zone is chosen as "Pacific Time (US)" or "Baja California" for example, as either will create the correct time conversions (I think). If I find multiple matches, I currently just pick the first found TimeZoneInfo match.
I can then convert my UTC dates from the database to local time:
DateTime clientDate = TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeZoneInfo);
Javascript
// Time zone. Sets two form values:
// tzBaseUtcOffset: minutes from UTC (non-DST)
// tzDstDayOffset: number of days from 1/1/2016 until first day of DST ; 0 = no DST
var form = document.forms[0];
var janOffset = -new Date(2016, 0, 1).getTimezoneOffset(); // Jan
var julOffset = -new Date(2016, 6, 1).getTimezoneOffset(); // Jul
var baseUtcOffset = Math.min(janOffset, julOffset); // non DST offset (winter offset)
form.elements["tzBaseUtcOffset"].value = baseUtcOffset;
// Find first day of DST (from 1/1/2016)
var dstDayOffset = 0;
if (janOffset != julOffset) {
var startDay = janOffset > baseUtcOffset ? 180 : 0; // if southern hemisphere, start 180 days into year
for (var day = startDay; day < 365; day++) if (-new Date(2016, 0, day + 1, 12).getTimezoneOffset() > baseUtcOffset) { dstDayOffset = day; break; } // noon
}
form.elements["tzDstDayOffset"].value = dstDayOffset;
C#
private TimeZoneInfo GetTimeZoneInfo(int baseUtcOffset, int dstDayOffset) {
// Converts client/browser data to TimeZoneInfo
// baseUtcOffset: minutes from UTC (non-DST)
// dstDayOffset: number of days from 1/1/2016 until first day of DST ; 0 = no DST
// Returns first zone info that matches input, or server zone if none found
List<TimeZoneInfo> zoneInfoArray = new List<TimeZoneInfo>(); // hold multiple matches
TimeSpan timeSpan = new TimeSpan(baseUtcOffset / 60, baseUtcOffset % 60, 0);
bool supportsDst = dstDayOffset != 0;
foreach (TimeZoneInfo zoneInfo in TimeZoneInfo.GetSystemTimeZones()) {
if (zoneInfo.BaseUtcOffset.Equals(timeSpan) && zoneInfo.SupportsDaylightSavingTime == supportsDst) {
if (!supportsDst) zoneInfoArray.Add(zoneInfo);
else {
// Has DST. Find first day of DST and test for match with sent value. Day = day offset into year
int foundDay = 0;
DateTime janDate = new DateTime(2016, 1, 1, 12, 0, 0); // noon
int startDay = zoneInfo.IsDaylightSavingTime(janDate) ? 180 : 0; // if southern hemsphere, start 180 days into year
for (int day = startDay; day < 365; day++) if (zoneInfo.IsDaylightSavingTime(janDate.AddDays(day))) { foundDay = day; break; }
if (foundDay == dstDayOffset) zoneInfoArray.Add(zoneInfo);
}
}
}
if (zoneInfoArray.Count == 0) return TimeZoneInfo.Local;
else return zoneInfoArray[0];
}
You can get this information from client to server (any web API call)
var timezoneOffset = new Date().getTimezoneOffset();
With the help of timezoneoffset details you can achieve the same. Here in my case i converted UTC DateTime to my client local datetime in Server side.
DateTime clientDateTime = DateTime.UtcNow - new TimeSpan(timezoneOffset / 60, timezoneOffset % 60, 0);
Click for code example
Take a look at this asp.net c# solution
TimeZoneInfo mytzone = TimeZoneInfo.Local;
System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_TIMEZONE"] ;
Related
I have a requirement which I'm getting a little confused about. I started using NodaTime which I think is the best way to go.
I have two users, User1 and User2 both in two different timezones. They are available to meet between 2pm and 5pm for example, in their local timezones. If User2 has an offset of +2 hours from User1, then the overlap is just 1 hour. What I want to get the number of hours overlap (the actual time for User1 and User2 would be a bonus.)
All I have got so far is:
var user1TimeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(user1timezone);
var user2TimeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(user2timeZone);
Any thoughts on how I should even start tackling this problem?
Thanks,
Firstly, be aware that it could change each day: don't treat a time zone as a fixed offset.
Secondly, be aware that the local time specified (for each of start/end) may not even happen, or may happen twice. Work out how you want to handle ambiguous and skipped times.
For any particular day, I would just convert they users' start/end times to Instant (via ZonedDateTime) and then you can find the overlap. This does assume that any overlap happens on the same day, however... that isn't the case in reality. I'm having a meeting soon where one of the attendees is in New Zealand - it's March 14th here, but March 15th there. Accounting for that is rather trickier...
Here's code for the relatively simple case though:
using NodaTime;
using System;
class Test
{
static void Main()
{
// My availability: 4pm-7pm in London
var jon = new Availability(
DateTimeZoneProviders.Tzdb["Europe/London"],
new LocalTime(16, 0, 0),
new LocalTime(19, 0, 0));
// My friend Richard's availability: 12pm-4pm in New York
var richard = new Availability(
DateTimeZoneProviders.Tzdb["America/New_York"],
new LocalTime(12, 0, 0),
new LocalTime(16, 0, 0));
// Let's look through all of March 2017...
var startDate = new LocalDate(2017, 3, 1);
var endDate = new LocalDate(2017, 4, 1);
for (LocalDate date = startDate; date < endDate; date = date.PlusDays(1))
{
var overlap = GetAvailableOverlap(date, jon, richard);
Console.WriteLine($"{date:yyyy-MM-dd}: {overlap:HH:mm}");
}
}
static Duration GetAvailableOverlap(
LocalDate date,
Availability avail1,
Availability avail2)
{
// TODO: Check that the rules of InZoneLeniently are what you want.
// Be careful, as you could end up with an end before a start...
var start1 = (date + avail1.Start).InZoneLeniently(avail1.Zone);
var end1 = (date + avail1.End).InZoneLeniently(avail1.Zone);
var start2 = (date + avail2.Start).InZoneLeniently(avail2.Zone);
var end2 = (date + avail2.End).InZoneLeniently(avail2.Zone);
var latestStart = Instant.Max(start1.ToInstant(), start2.ToInstant());
var earliestEnd = Instant.Min(end1.ToInstant(), end2.ToInstant());
// Never return a negative duration... return zero of there's no overlap.
// Noda Time should have Duration.Max really...
var overlap = earliestEnd - latestStart;
return overlap < Duration.Zero ? Duration.Zero : overlap;
}
}
public sealed class Availability
{
public DateTimeZone Zone { get; }
public LocalTime Start { get; }
public LocalTime End { get; }
public Availability(DateTimeZone zone, LocalTime start, LocalTime end)
{
Zone = zone;
Start = start;
End = end;
}
}
If you have a server where you do that, you have to send UTC and then compare it. When you get the time on the client side you have to convert it into local. It means, that when first user wants to arrange a meeting, he sends his time into UTC to server, then when second user gets this time, he will convert it into his local time.
// First user sends UTC.
DateTime firstUserTime = DateTime.UtcNow;
// Second user gets time in his time zone.
DateTime secondUserTime = firstUserTime.ToLocalTime();
In this massively oversimplified example, I have a controller method that accepts a DateTime
[Route("api/demo)]
public IHttpActionResult Post(DateTime date)
{
// format dateTime here
}
We call this from the client with Javascript.
var data = {
date: new Date()
};
$.ajax({
url: "/api/demo",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(data),
});
The new Date() part is what I feel is the important part, as we're trying to record the date as the calling client sees it (their local time)
What is the best way to format the DateTime object as a string, so that it records the timezone information, and can be parsed back into a DateTime object again later if required?
(We're storing this formatted string in an analytics recording platform / data warehouse)
You don't need to perform any conversions, just change the parameter type to DateTimeOffset:
[Route("api/demo)]
public IHttpActionResult Post(DateTimeOffset date)
{
//use the date without conversions.
}
JSON.stringify serializes the date using the ISO8601 format (eg "2017-01-10T14:52:04.780Z") which can be parsed directly to a DateTimeOffset. DateTimeOffset allows you to compare values with different offsets directly, removing the need to convert to the same timezone
By using DateTimeOffset you avoid the confusion between local and UTC DateTime values. Without knowing the timezone offset you don't really know what "local" refers to - the client's or the server's timezone?
You can use new Date().getTimezoneOffset() in javascript to know the difference between the current time zone of the client and the UTC. It offset will be in minute. Example - TimezoneOffset between Singapore Time and UTC is -480 minutes.
http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp
Then create a cookie in the javascript and store that offset in it.
function setTimezoneCookie(){
var timezone_cookie = "timezoneoffset";
if (!$.cookie(timezone_cookie)) {
// create a new cookie
$.cookie(timezone_cookie, new Date().getTimezoneOffset());
}
}
Every request goes to the server will carry that cookie and at server side
convert the dateTime submitted by client to UTC by Adding the offset from cookie and save it in the database. This would ensure that no matter in what timezone user is the data will always have UTC date and time uniformly.
Also when displaying the datetime information in the UI, convert it to the client time by substracting offset retrieved from cookie before sending to the UI.
This way it will be sure that user sees the dates and time as per it's client machines timezone.
Extension methods would be handy in this case.
public static DateTime ToClientTime(this DateTime dt)
{
// read the value from session
var timeOffSet = HttpContext.Current.Request["timezoneoffset"];
if (timeOffSet != null)
{
var offset = int.Parse(timeOffSet.ToString());
dt = dt.AddMinutes(-1 * offset);
return dt;
}
// if there is no offset in session return the datetime as it is
return dt;
}
public static DateTime ToUtcTime(this DateTime dt)
{
// read the value from session
var timeOffSet = HttpContext.Current.Request["timezoneoffset"];
if (timeOffSet != null)
{
var offset = int.Parse(timeOffSet.ToString());
dt = dt.AddMinutes(offset);
return dt;
}
// if there is no offset in session return the datetime as it is
return dt;
}
This should resolve help you resolving your issue.
This question already has answers here:
How Convert UTC Date & time to local time using different timezone Nodatime
(2 answers)
Closed 8 years ago.
I heard that if I use nodatime library then I can get date & time based on timezone id.
first I change my pc date and time. set to old date and time in my pc and then run the below code which disappoint me.
using NodaTime;
var zoneId = "Asia/Kolkata";
DateTimeZone _zone = DateTimeZoneProviders.Tzdb[zoneId];
ZonedDateTime _now = SystemClock.Instance.Now.InZone(_zone);
var xx = _now.LocalDateTime;
Below code display wrong date & time because I set my pc date & time to few days back.
Is there any way that if date & time is wrong but still code display right date & time without depending on user pc date & time setting using Noda Time library. Looking for suggestion.
UPDATE
i follow this way but not sure am i on right tract to achieve my goal.
public static DateTime GetFastestNISTDate()
{
var result = DateTime.MinValue;
DateTime utcDateTime= DateTime.MinValue;
// Initialize the list of NIST time servers
// http://tf.nist.gov/tf-cgi/servers.cgi
string[] servers = new string[] {
"nist1-ny.ustiming.org",
"nist1-nj.ustiming.org",
"nist1-pa.ustiming.org",
"time-a.nist.gov",
"time-b.nist.gov",
"nist1.aol-va.symmetricom.com",
"nist1.columbiacountyga.gov",
"nist1-chi.ustiming.org",
"nist.expertsmi.com",
"nist.netservicesgroup.com"
};
// Try 5 servers in random order to spread the load
Random rnd = new Random();
foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
{
try
{
// Connect to the server (at port 13) and get the response
string serverResponse = string.Empty;
using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
{
serverResponse = reader.ReadToEnd();
}
// If a response was received
if (!string.IsNullOrEmpty(serverResponse))
{
// Split the response string ("55596 11-02-14 13:54:11 00 0 0 478.1 UTC(NIST) *")
string[] tokens = serverResponse.Split(' ');
// Check the number of tokens
if (tokens.Length >= 6)
{
// Check the health status
string health = tokens[5];
if (health == "0")
{
// Get date and time parts from the server response
string[] dateParts = tokens[1].Split('-');
string[] timeParts = tokens[2].Split(':');
// Create a DateTime instance
DateTime utcDateTime = new DateTime(
Convert.ToInt32(dateParts[0]) + 2000,
Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[2]),
Convert.ToInt32(timeParts[0]), Convert.ToInt32(timeParts[1]),
Convert.ToInt32(timeParts[2]));
// Convert received (UTC) DateTime value to the local timezone
//result = utcDateTime.ToLocalTime();
return utcDateTime;
// Response successfully received; exit the loop
}
}
}
}
catch
{
// Ignore exception and try the next server
}
}
return result;
}
var wc = GetFastestNISTDate();
var pattern = InstantPattern.CreateWithInvariantCulture("dd/MM/yyyy HH:mm:ss");
var parseResult = pattern.Parse(wc.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
if (!parseResult.Success)
throw new InvalidDataException("...whatever...");
var instant = parseResult.Value;
var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
var zonedDateTime = instant.InZone(timeZone);
var bclDateTime = zonedDateTime.ToDateTimeUnspecified();
If you can't trust the computer's clock, then you must get the time from another source, such as from a network server via NTP connection. Noda Time does not have this functionality.
You may be interested in this answer which describes how to query an NTP server in C#. Note that at the very end of the code in that answer it calls ToLocalTime. Instead, you would use Noda Time's Instant.FromDateTimeUtc method.
I pick up data which includes some date columns. Date returned from database is in UTC format. I feed this data to report viewer and want to show the date in local format, considering daylight saving.
I can do that from server side but I want the conversion to be according to the client machine timezone.
Is there any way to do it ?
Is your client a web page or a .NET app? If it is a .NET app you could do it like this. Firstly send your client timezone to your server like so:
string clientTimeZone = TimeZoneInfo.Local.ToSerializedString();
Then on your server:
var clientTimeZoneInfo = TimeZoneInfo.FromSerializedString(clientTimeZone);
var localDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, clientTimeZoneInfo);
If this is a webapp use this javascript to send the offset to the server:
var timeNow = new Date();
var timezone = timeNow.getTimezoneOffset() / 60 * (-1);
Then on your server:
string clientTimeZoneOffset = "8";
var clientTimeZoneInfo = TimeZoneInfo.CreateCustomTimeZone("client", new TimeSpan(0, Int32.Parse(clientTimeZoneOffset), 0, 0),
"client", "client");
var utcDateTime = DateTime.UtcNow;
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, clientTimeZoneInfo);
I'm using several literals to inject the user's time onto the the page. The values in the HTML are the UTC times.
var TheDay = parseInt($('#UserDayToday').html(), 10);
var TheMonth = parseInt($('#UserMonthToday').html(), 10);
var TheYear = parseInt($('#UserYearToday').html(), 10);
var TheHours = parseInt($('#UserTimeStampHours').html(), 10);
var TheMinutes = parseInt($('#UserTimeStampMinutes').html(), 10);
Now I want to build a time stamp with that time so I tried this:
var TheDateToday = new Date();
TheDateToday.setUTCFullYear(TheYear, TheMonth, TheDay);
TheDateToday.setUTCHours(TheHours, TheMinutes, 0, 0);
alert(TheDateToday);
When the alert comes on, it gives me the time with his timezone shift added. How can I just have the the UTC time. I know I can get it from the browser but I want to get the UTC time built from the data sent from the server, not retrieved from the user's machine by the browser.
Thanks
You are displaying the date in local time. Use the toUTCString method instead of the implicit toString method:
alert(TheDateToday.toUTCString());