Reputation: 1059
I am passed a DateTime
object and a string
timezone variable separately. Is there a way to cast this DateTime as the timezone in the string without "converting"(changing the actual time)?
Upvotes: 0
Views: 2776
Reputation: 885
If your time zone string is very specifically one of the system-defined strings, you can definitely do this. The easiest way is to make the assumption that the DateTime passed in is already in UTC, and that the string passed in is one of the Id values listed in TimeZoneInfo.GetSystemTimeZones()
. Your function would look something like this:
public DateTime ConvertUtcDateTime(DateTime utcDateTime, string timeZoneId)
{
var tz = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
var convertedDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, tz);
return convertedDateTime;
}
This would create a "new" DateTime value, and your original utcDateTime value would be unchanged. If you can't assume that the DateTime value is UTC, you'll have to require both the source and destination time zones and your function would change slightly:
public DateTime ConvertDateTime(DateTime currentDateTime, string sourceTimeZoneId, string destinationTimeZoneId)
{
var tzSource = TimeZoneInfo.FindSystemTimeZoneById(sourceTimeZoneId);
var tzDestination = TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZoneId);
var convertedDateTime = TimeZoneInfo.ConvertTime(currentDateTime, tzSource, tzDestination);
return convertedDateTime;
}
Keep in mind that in both of these functions, you need to test if the time zone returned by TimeZoneInfo.FindSystemTimeZoneById
is not null. If it is, your input string was bad and you will need to handle that. An exception would likely work well there, but I don't know your needs.
Edit:
As an afterthought, if your strings aren't exactly the same as the Id values from TimeZoneInfo.GetSystemTimeZones()
, but they do kind of match up one-to-one, you could make some kind of Dictionary<string, string>
to map your time zone strings to the system's Id values and run from that. That's a good bit of hard-coding, though, but sometimes you need something like this if your inputs can't be changed.
Upvotes: 1
Reputation: 1957
Use UTC Time.
To implelent it, follow this code.
var currentDate = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc);
Upvotes: 1
Reputation: 3551
DateTime
itself is immutable in C# so you can't really change it like you are wanting to.
Your best bet would be to store the object as a UTC DateTime and then based on the timezone string you are passed, add or subtract time from that to "correct" the UTC time stamp.
Upvotes: 0