I need to get real DateTime by CultureInfo object. For example, my site is on US company server (that has own US time) but site is for Italy (example), where time is different, and on the site I should show Italy time, not US. In web.congig I have currentCulture="it-It"
Is it possible to get time for site and if so, what is the right way to do it?
Actually it would be great to have a function like:
public static DateTime GetSiteDate(CultureInfo ci)
{
....
return siteDate;
}
Thanks!
It is likely not possible to get the local time based on culture alone, mostly because time zones don't correspond one-to-one to countries. While Italy's time zone is Central European Standard Time (if I'm not mistaken), it will not always be the case that each country has a single time zone. For example, in the United States there are at least four time zones.
to find date DateTime.Now();
to find zone DateTime.Zone();
If you need much, there is no chance in ASP.NET you have to make use of Java Scripts to fulfill your needs.
Related
Our application was designed to handle user from different Geographic location.
We are unable to detect what is the current end user local time and
time zone operate on it. They select different culture like sv-se,
en-us, ta-In even they access from Europe/London timezone..
We hosted it in a hosting server in US, application users are from Norway/Denmark/Sweden/UK/USA/India
The problem is we used DateTime.Now to store the record created/updated date, etc.
Since the Server runs in USA all user data are saved as US time :(
After researching in SO, we decided to stored all history dates in DB as DateTime.UtcNow
PROBLEM:
There is a record created on 29 Dec 2013, 3:15 P.M Swedish time.
public ActionResult Save(BookingViewModel model)
{
Booking booking = new Booking();
booking.BookingDateTime = model.BookingDateTime; //10 Jan 2014 2:00 P.M
booking.Name = model.Name;
booking.CurrentUserId = (User)Session["currentUser"].UserId;
//USA Server runs in Pacific Time Zone, UTC-08:00
booking.CreatedDateTime = DateTime.UtcNow; //29 Dec 2013, 6:15 A.M
BookingRepository.Save(booking);
return View("Index");
}
We want to show the same history time to the user who logged in in India/Sweden/USA.
As of now we are using current culture user logged in and choose the timezone from a config file and using for conversion with TimeZoneInfo class
<appSettings>
<add key="sv-se" value="W. Europe Standard Time" />
<add key="ta-IN" value="India Standard Time" />
</appSettings>
private DateTime ConvertUTCBasedOnCulture(DateTime utcTime)
{
//utcTime is 29 Dec 2013, 6:15 A.M
string TimezoneId =
System.Configuration.ConfigurationManager.AppSettings
[System.Threading.Thread.CurrentThread.CurrentCulture.Name];
// if the user changes culture from sv-se to ta-IN, different date is shown
TimeZoneInfo tZone = TimeZoneInfo.FindSystemTimeZoneById(TimezoneId);
return TimeZoneInfo.ConvertTimeFromUtc(utcTime, tZone);
}
public ActionResult ViewHistory()
{
List<Booking> bookings = new List<Booking>();
bookings=BookingRepository.GetBookingHistory();
List<BookingViewModel> viewModel = new List<BookingViewModel>();
foreach (Booking b in bookings)
{
BookingViewModel model = new BookingViewModel();
model.CreatedTime = ConvertUTCBasedOnCulture(b.CreatedDateTime);
viewModel.Add(model);
}
return View(viewModel);
}
View Code
#Model.CreatedTime.ToString("dd-MMM-yyyy - HH':'mm")
NOTE: The user can change the culture/language before they login. Its a localization based application, running in US server.
I have seen NODATIME, but I could not understand how it can help with multi culture web application hosted in different location.
Question
How can I show a same record creation date 29 Dec 2013, 3:15 P.M for the users logged in INDIA/USA/Anywhere`?
As of now my logic in ConvertUTCBasedOnCulture is based user logged in culture. This should be irrespective of culture, since user can login using any culture from India/USA
DATABASE COLUMN
CreatedTime: SMALLDATETIME
UPDATE: ATTEMPTED SOLUTION:
DATABASE COLUMN TYPE: DATETIMEOFFSET
UI
Finally I am sending the current user's local time using the below Momento.js code in each request
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
try {
//moment.format gives current user date like 2014-01-04T18:27:59+01:00
jqXHR.setRequestHeader('BrowserLocalTime', moment().format());
}
catch (e) {
}
}
});
APPLICATION
public static DateTimeOffset GetCurrentUserLocalTime()
{
try
{
return
DateTimeOffset.Parse(HttpContext.Current.Request.Headers["BrowserLocalTime"]);
}
catch
{
return DateTimeOffset.Now;
}
}
then called in
model.AddedDateTime = WebAppHelper.GetCurrentUserLocalTime();
In View
#Model.AddedDateTime.Value.LocalDateTime.ToString("dd-MMM-yyyy - HH':'mm")
In view it shows the local time to user, however I want to see like dd-MMM-yyyy CET/PST (2 hours ago).
This 2 hours ago should calculate from end user's local time. Exactly same as stack overflow question created/edited time with Timezone display and local user calculation.
Example: answered Jan 25 '13 at 17:49 CST (6 hours/days/month ago) So the other viewing from USA/INDIA user can really understand this record was created exactly 6 hours from INDIA/USA current time
Almost I think I achieved everything, except the display format & calculation. How can i do this?
It sounds like you need to store a DateTimeOffset instead of a DateTime. You could just store the local DateTime to the user creating the value, but that means you can't perform any ordering operations etc. You can't just use DateTime.UtcNow, as that won't store anything to indicate the local date/time of the user when the record was created.
Alternatively, you could store an instant in time along with the user's time zone - that's harder to achieve, but would give you more information as then you'd be able to say things like "What is the user's local time one hour later?"
The hosting of the server should be irrelevant - you should never use the server's time zone. However, you will need to know the appropriate UTC offset (or time zone) for the user. This cannot be done based on just the culture - you'll want to use Javascript on the user's machine to determine the UTC offset at the time you're interested in (not necessarily "now").
Once you've worked out how to store the value, retrieving it is simple - if you've already stored the UTC instant and an offset, you just apply that offset and you'll get back to the original user's local time. You haven't said how you're converting values to text, but it should just drop out simply - just format the value, and you should get the original local time.
If you decide to use Noda Time, you'd just use OffsetDateTime instead of DateTimeOffset.
Standard approach is to always store any time data as UTC if particular moment in time is important. That time is not impacted by time zone changes and cultures.
Most common approach to showing time with time zone is to store time as UTC and convert to current user's culture/time zone combination when you display the value. This approach only requires single date time filed in the storage.
Note that for Web cases (like ASP.Net) you may need to figure out user's culture/time zone first and send it to server (as this information is not necessary available on GET requests) or do formatting of time in the browser.
Depending what "show the same history time" you may need to store additional information like current culture and/or current offset. If you need to show time exactly as original user seen it you may also save string representation (because formats/translations can change later and value will look different, also it is unusual).
Note: culture and time zone are not tied together, so you'll need to decide how you need to handle cases like IN-IN culture in US PST time zone.
I'm a little confused by the phrasing of your question, but it appears that you would like to determine the time zone of your user.
Have you tried asking them? Many applications have the user pick their time zone in user settings.
You could pick from a drop-down list, or a pair of lists (country, then time zone within the country), or from a map-based time zone picker control.
You could take a guess and use that as the default unless your user changes it.
If you go down that route, you will need to be able to use IANA/Olson time zones, which is where Noda Time comes into play. You can access them from DateTimeZoneProviders.Tzdb.
The hosting location is irrelevant if you are using UTC. That's a good thing.
Also, if you're using Noda Time, then you probably should use SystemClock.Instance.Now instead of DateTime.UtcNow.
See also here and here.
Also - an alternative solution would be just to pass the UTC time to the browser and load it into a JavaScript Date object. The browser can convert that to the user's local time. You could also use a library like moment.js to make this easier.
Update
Regarding your approach of mapping culture codes to time zones:
<appSettings>
<add key="sv-se" value="W. Europe Standard Time" />
<add key="ta-IN" value="India Standard Time" />
</appSettings>
That will not work, for several reasons:
Many people use a different culture setting on their computer than the area that they are physically in. For example, I might be an a US-English speaker living in Germany, my culture code is likely still en-US, not de-DE.
A culture code containing a country is used to distinguish between dialects of a language. When you see es-MX, that means "Spanish, as spoken in Mexico". It does not mean that the user is actually in Mexico. It just means that user speaks that dialect of Spanish, as compared to es-ES which means "Spanish, as spoken in Spain".
Even if the country portion of the culture code could be reliable, there are many countries that have multiple time zones! For example, what would you put in your mapping list for en-US? You can't just assume that we are all on Eastern Standard Time.
Now, I've explained why your current approach won't work, I strongly suggest you take my original advice. Very simply:
Determine the time zone of the user, preferably by asking them, perhaps with some assistance by one of the utilities I linked to above.
You're storing UTC, so just convert to that time zone for display.
Using Microsoft Time Zones
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
DateTime localDatetime = TimeZoneInfo.ConvertTimeFromUtc(yourUTCDateTime, tz);
Using IANA Time Zones and Noda Time
DateTimeZone tz = DateTimeZoneProviders.Tzdb["Europe/Stockholm"];
Instant theInstant = Instant.FromDateTimeUtc(yourUTCDateTime);
LocalDateTime localDateTime = theInstant.InZone(tz);
We faced a similar problem with an application I worked on recently. During development every one was in the same time zone and the issue wasn't noticed. And in any case there was a lot of legacy code that would have been a pain to change not to mention converting all the date time info that was already in the DB. So changing to DateTimeOffset was not an option. But we managed to get it all consistent by converting from server time to user time on the way out and converting from user time to server time on the way in. It was also important to do this with any date time comparisons that were a boundary. So if a user expected some thing to expire midnight their time then we would convert that time to server time and do all comparisons in server time. This sounds like a lot of work but was much less work then converting the entire application and DB to use DateTimeOffsets.
Hear is a thread that looks like has some good solutions to the time zone issue.
Determine a User's Timezone
If you want to show consistent date/time history to the user, regardless of the locale they are viewing the history from, then:
During Save, store not only UTC "creation" date/time, but also the detected locale
Use stored saved from locale to compute original date/time and emit a string to display (i.e. do not use current user locale when you're diplaying it)
If you don't have the ability to amend your storage, then perhaps you can change your submit to send the "current client time", store it literally (do not convert to UTC) and then display literally (do not convert to detected culture)
But as I say in my comment under your question, I am not certain I got your requirements right.
Hello!
I was confused in the problem of time zones. I am writing a web application that will contain some news with dates of publication, and I want the client to see the date of publication of the news in the form of corresponding local time. However, I do not know in which time zone the client is located.
I have three questions.
I have to ask just in case: does DateTimeOffset.UtcNow always returns the correct UTC date and time, regardless of whether the server is dependent on daylight savings time? For example, if the first time I get the value of this property for two minutes before daylight savings time (or before the transition from daylight saving time back) and the second time in 2 minutes after the transfer, whether the value of properties in all cases differ by only 4 minutes? Or here require any further logic? (Question #1)
Please see the following example and tell me what you think.
I posted the news on the site. I assume that DateTimeOffset.UtcNow takes into account the time zone of the server and the daylight savings time, and so I immediately get the correct UTC server time when pressing the button "Submit". I write this value to a MS SQL database in the field of type datetime2(0).
Then the user opens a page with news and no matter how long after publication. This may occur even after many years. I did not ask him to enter his time zone. Instead, I get the offset of his current local time from UTC using the javascript function following way:
function GetUserTimezoneOffset()
{
var offset = new Date().getTimezoneOffset();
return offset;
}
Next I make the calculation of the date and time of publication, which will show the user:
public static DateTime Get_Publication_Date_In_User_Local_DateTime(
DateTime Publication_Utc_Date_Time_From_DataBase,
int User_Time_Zone_Offset_Returned_by_Javascript)
{
int userTimezoneOffset = User_Time_Zone_Offset_Returned_by_Javascript; // For
// example Javascript returns a value equal to -300, which means the
// current user's time differs from UTC to 300 minutes. Ie offset
// is UTC +6. In this case, it may be the time zone UTC +5 which
// currently operates summer time or UTC +6 which currently operates the
// standard time.
// Right? (Question #2)
DateTimeOffset utcPublicationDateTime =
new DateTimeOffset(Publication_Utc_Date_Time_From_DataBase,
TimeSpan.Zero); // get an instance of type DateTimeOffset for the
// date and time of publication for further calculations
DateTimeOffset publication_DateTime_In_User_Local_DateTime =
utcPublicationDateTime.ToOffset(new TimeSpan(0, - userTimezoneOffset, 0));
return publication_DateTime_In_User_Local_DateTime.DateTime;// return to user
}
Is the value obtained correct? Is this the right approach to solving this problem? (Question #3)
UPDATED Oct 19 at 6:58 (I tried post it as a comment but it's too long by 668 characters)
Matt Johnson, Thank You for such a detailed answer despite that of the fact that you are doing this not the first time. Thank you for taking the time to explain this particular case, and not just provide links to other posts.
I have read the information that you have provided. Maybe I'm still not fully aware of all the details, but if I understand it right, for the right convertion of DateTime (which was written many years ago in the database) from UTC to the same user's moment, I need to know UTC offset which he had at that moment. And it is difficult taking into account that transfer rules for DST change constantly. And even now, though the platform ".NET" contains some TZDB that is used for the TimeZoneInfo type, I can't take advantage of it without the exact position of the user.
But what if I am only interested in the date and time of starting this year, and only in Russia, where DST was canceled in 2011? As I understand it, this means that if properly configured clock on user's computer, located in Russia, this approach will always give the correct result. And since 2011, the offset to UTC of user's clock should always be the same. Accordingly, the shift indicators in different browsers will not be different for the Russian user's.
Answer to Question 1
... does DateTimeOffset.UtcNow always returns the correct UTC date and time, regardless of whether the server is dependent on daylight savings time?
Yes. As long is your clock is set correctly, UtcNow always refers to the UTC time. The time zone settings of the server will not affect it. The value in your example will always be 4 minutes, regardless of DST.
Answer to Question 2
var offset = new Date().getTimezoneOffset();
Since new Date() returns the current date and time, this will return you the current offset. You then proceed to apply this current offset to some past value, which may or may not be the correct offset for that specific time. Please read the timezone tag wiki, especially the section titled "Time Zone != Offset".
Answer to Question 3
Is the value obtained correct? Is this the right approach to solving this problem?
No. This is not the correct approach. You have a few options:
First Option
Just pass the UTC value to JavaScript without modification.
Send it in ISO8601 format, such as 2013-10-18T12:34:56.000Z. You can get this in .Net easily using yourDateTime.ToString("o").
Be sure the DateTime you are starting with has .Kind == DateTimeKind.Utc, otherwise it won't get the Z on the end, which is essential.
If you are targeting older browsers that can't parse ISO8601, then you will need a library such as moment.js to parse it for you.
Alternatively, you could pass the number of milliseconds since 1/1/1970 UTC as a number and load that into a JavaScript Date instead of parsing.
Now you can just display the Date object using JavaScript. Let the browser convert it from UTC to the users local time.
Warning, with this approach, some conversions might be incorrect due to the problem I describe here.
Second Option
Like the first option, pass the UTC timestamp to JavaScript
Use that to get the offset for that timestamp.
Pass the offset back to the server in a postback or ajax call.
Apply the offset on the server
Output the local time zone
I don't particularly like this option because of the round trip. You might as well calculate it in JavaScript like the first option.
Third Option
Get the user's time zone. The best way is to ask them for it, usually on a user setting page.
Use it to convert from the UTC time to their local time completely on the server.
You can use Windows time zones and the TimeZoneInfo class to do the conversions.
Or you can use IANA/Olson time zones and the Noda Time library.
If you do this, you can optionally use a map-based timezone picker.
You can take a guess at the user's time zone with jsTimeZoneDetect.
This approach is more accurate, but requires more user interaction.
Also, please in future posts, ask just one question at a time. And please search before you post - I've written most of this in one form or another many times before.
I am working on a web app using .NET MVC 3 and SQL server 2008 (r2).
Anyway, I have a date time object and I want to convert it to user time. It is fairly trivial to convert right now to user time; I have some java script that will get me the users offset from UTC. And I know my date times offset to UTC.
What I realized yesterday, is that my user's offsets will change, if they live in a pesky area of the world. And that would cause old dates and time to be wrong by some amount of time.
Now I know C# has some utilities to convert into a time zones time, but do they really handle all of the intricacies of daylights savings?
For example. If I have a time, 10-10-2001 8:00:00 how do I get that into pacific time? Or if i have 6-6-2004, how do i get that into pacific time?
Since the dates change for the roll overs, it is pretty complex, and I would like a general solution that does not require maintenance to set up date ranges for time zones.
I know this is a classic problem in CS, but I cannot find something that really answers my question 100%. From what I have seen: C# uses the current year's daylights savings dates to change every years date times. Which could cause some mistakes.
Thank you so much for the help.
Now I know C# has some utilities to convert into a time zones time, but do they really handle all of the intricacies of daylights savings?
TimeZoneInfo does, yes1. (It's part of the .NET framework, not part of C# - C# is just the language you happen to be using.) However, I don't think that's what you really want to do.
Why are you storing the DateTime in the server's time zone anyway? It would be more sensible to store it in UTC, in most cases. Aside from anything else, if your server is in a time zone which observes daylight saving time, you will end up with ambiguity for one hour per year, when the clock goes back. (The same local time occurs twice.)
Once you've stored it as UTC, you should give it to your Javascript client as UTC too. While you say that you have "some java script that will get me the users offset from UTC" - that will depend on the exact instant in time. For example, as I'm in the UK, my offset is sometimes 0 and sometimes +1 hour. If you pass the UTC back to the client, that can work out the local time from that UTC time. Your server can't, unless you can get an accurate representation of the time zone from the client to the server, which is generally a tricky thing to do.
From what I have seen: C# uses the current year's daylights savings dates to change every years date times.
Again, C# itself isn't relevant here. It's not clear which part of the .NET framework you mean - TimeZone? TimeZoneInfo? DateTime? TimeZoneInfo has historical data, but only if you're on an operating system version which supports it.
1 Well, as far as you're likely to care. It doesn't have as much historical data as TZDB, and it has some very odd representations for Russia and Namibia, but it does generally have the idea of rules changing.
I have found the following rules to be the best solution:
At server-side use UTC. No need to deal with Time Zones at all. That means that if you store dates in database, use UTC dates, if you generate dates in server side use generally UTC (e.g: var nowDate =DateTime.UtcNow). The server dates should be location agnostic and that way there is no confusion.
At client-side use UTC as well when dealing with raw data, but display the dates in the UI converted to the browser's local time (which will be whatever time is configured in the operating system).
The good news is that this is already a built in capability in browsers! we just need to make it easier for them to handle it.
This means that if we have a javascript client code POSTing/PUTing/PATCHing data to a server and GETting data from the server using JSON, the JSON should use the ISO 8601 (natively supported) in UTC (ended in Z) as if you were doing:
var dateNow = new Date(); //Wed May 11 2016 13:06:21 GMT+1200 (New Zealand Standard Time)
var dateNowIso = dateNow.toISOString(); //"2016-05-11T01:06:21.147Z"
And then, simply rely on the browser capability to convert automatically any UTC date to the current local time and vice versa. The browser's javascript engine will be able to display in the UI the correct local time as long as the format is a Date object.
NOTE on how to implement it for a .NET server & Javascript client scenario: For example, I am using AngularJS (with restangular) in my client javascript code and MVC 6 (ASP.NET Core 1.0) in server side.
The JSON that comes from the server might contain date properties, but in JSON the type is a string such as:
{
"myDateField":"2016-05-11T05:00:00Z"
}
In order to rely on the browser's capability to handle properly UTC times and convert them to local browser's time I need to parse this UTC date string into a real javascript Date object, so I use a regular expression to match any text value that looks like a UTC date in ISO 8601 format (in my case this code is in a restangular response interceptor but it could be anywhere):
const regexIso8601 = /((((\d{4})(-((0[1-9])|(1[012])))(-((0[1-9])|([12]\d)|(3[01]))))(T((([01]\d)|(2[0123]))((:([012345]\d))((:([012345]\d))(\.(\d+))?)?)?)(Z|([\+\-](([01]\d)|(2[0123]))(:([012345]\d))?)))?)|(((\d{4})((0[1-9])|(1[012]))((0[1-9])|([12]\d)|(3[01])))(T((([01]\d)|(2[0123]))(([012345]\d)(([012345]\d)(\d+)?)?)?)(Z|([\+\-](([01]\d)|(2[0123]))([012345]\d)?)))?))/;
function convertDateStringsToDates(input: any): void {
// Ignore things that aren't objects.
if (typeof input !== "object") {
return input;
}
for (var key in input) {
if (!input.hasOwnProperty(key)) {
continue;
}
let value = input[key];
let match: RegExpMatchArray;
// Check for string properties which look like dates.
if (angular.isArray(value)) {
angular.forEach(value, (val, key) => {
convertDateStringsToDates(val);
});
} else if (angular.isString(value) && (match = value.match(regexIso8601))) {
let milliseconds = Date.parse(match[0]);
if (!isNaN(milliseconds)) {
input[key] = new Date(milliseconds);
}
} else if (angular.isObject("object")) {
// Recurse into object
convertDateStringsToDates(value);
}
}
}
That way I can use my javascript object with proper Date objects.
In the server side (either MVC6 or WebAPI2..) I have an instruction to tell my JSON parser to ALWAYS use UTC formats when parsing Dates, otherwise it wouldn't add the Z character at the end, which is very important. Example for MVC6:
services.AddMvc().AddJsonOptions(opt => {
// json dates always in javascript date format with UTC e.g: "2014-01-01T23:28:56.782Z"
opts.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
});
Inspired by this article
UPDATE: There are scenarios where it might be interesting to store data in local time as stated in the comments below.
i'm a little lost in the timezone :)
I have data stored with the time in UTC.
The server is in the Netherlands, so we live in utc+1 (now, with daylightsavingtime, in utc + 2)
Now a client says: give me the data from august 5th.
So i have to calculate the utc time from 'his time'.
For that i have to know:
what is your utc offset (we stored that in his profile, let's say utc -6)
are you in daylightsavingtime (because then we have to add +1 and make the utc offset -5)
Then my questions:
Can i ask the .Net framework: does country XX have daylightsavingtime?
Can i ask the .Net framework: is 08-05-2010T00:00:00 in country XXX daylightsavingtime at that moment?
i've been trying the .ToLocalTime(), but this only gives me the local time at the server, and that's not what i want, i want to calculate with the timezone of the user, and also with the fact that at that particular point in time, if he/she is in daylightsavingtime
I've also seen this VB example:
TimeZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")
Dim Dated As DateTime = TimeZoneInfo.ConvertTimeToUtc(TempDate, TimeZone)
but imho this doesn't take into account that the user in this timezone is or is not in a daylightsavingtime (dst) country.
For instance, one user in this timezone is in the netherlands having dst, and one other is in another country which has no dst.
You can't ask the framework about a particular country - but you can ask about a particular time zone.
TimeZoneInfo does take DST into account. (Heck, it wouldn't have the IsDaylightSavingTime method otherwise.) If you've got two users, one of whom is currently observing DST and the other of whom isn't, then they aren't in the same time zone.
If you could specify which locations you're talking about, I could try to find out which time zones are involved. (It's generally easier to find out the Olson names, but it shouldn't be impossible to find out the Windows IDs.)
TimeZone class has a method IsDaylightSavingTime that take a date as parameter
and return a boolean indicating if that date in in daylightsavingtime for that timezone.
I promote my comment to an answer.
It appears to be a complicate problem. Look at http://www.timeanddate.com/time/dst2010.html, there is a table of DST in various country of the world. You cannot get this with static code because DST change not only from country to country, but also from year to year.
I guess you have to maintain a table with DST information and get information from it.
Or you can query a webservice to get such infos.
Look at http://www.earthtools.org/webservices.htm#timezone for a webservice that you can query to get time in various country that take in account DST (it work only for Western Europe time zones).
Also look at http://www.geonames.org/export/web-services.html. You have to get your users geolocation to use these services.
I'm looking to implement a function with a signature something like the following:
bool IsTimeZoneValid(string countryCode, DateTime localTime);
The intention is to determine whether the country has a time zone in which the local time would be valid, given that we know the current UTC time. Let's say, for the sake of argument, that "valid" means that when converted to UTC the time is +/- 30 minutes from what we believe the time is.
For example, say it is currently 03/08/2009 18:25:00 UTC then given the following method call for Australia, it should return true as this is a valid time in the "Eastern Standard Time" zone:
IsTimeZoneValid("AU", DateTime.Parse("04/08/2009 03:25:00"));
However the following call for France should fail as this is not a valid time in France's time zone.
IsTimeZoneValid("FR", DateTime.Parse("04/08/2009 03:25:00"));
This needs to be accurate, and take into account daylight saving time etc.
.NET 3.5 includes the new TimeZoneInfo class which can do a lot of the conversion for me if I know what time zones exist in a specific country, but I can't seem to find any built-in lookup for this. Am I missing something, or am I going to have to manually create a table of country to time zone mappings?
To reiterate, my question is: Given a country code, how can I get a list of time zones. Alternatively, is there another way to approach this that I've missed?
By default windows only adds Time Zone info for you local time zone, which may be the cause of the problem.
This class works only for the local time zone and any predefined time zones. If you want to use this for other times zones, you must have the registry settings added to the machine for all time zones needed or create custom time zone info using CreateCustomTimeZone.
http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx?ppud=4
http://msdn.microsoft.com/en-us/library/bb384268.aspx