Reputation: 207
I need to Convert DateTime from UTC to local time, For that I had Validated the date time before converting to local time using TimeZoneInfo IsInValidTime method.
I'm getting Invalid date time for a particular date time, How to convert this date to a valid one?
Here is the Sample code:
_timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var dateTime = "10/03/2013 2:12:00 AM";
DateTime universalFormatDateTime = Convert.ToDateTime(dateTime).GetUniversalFormatDateTime();
if (_timeZoneInfo.IsInvalidTime(universalFormatDateTime)) Console.Write("Invalid DateTime\n");
Upvotes: 0
Views: 2612
Reputation: 2952
You should specify the DateTimeKind of your Date time. Add this before perform the validation:
universalFormatDateTime = DateTime
.SpecifyKind(universalFormatDateTime,DateTimeKind.Local);
Upvotes: 0
Reputation: 2020
What framework are you using?
Isn't ToUniversalTime() the correct choice?
DateTime universalFormatDateTime = Convert.ToDateTime(dateTime).ToUniversalTime()
Upvotes: 1
Reputation: 7894
I guess this is what you're trying to achieve:
_timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var dateTime = "10/03/2013 2:12:00 AM";
DateTime universalFormatDateTime = Convert
.ToDateTime(dateTime, new CultureInfo("en-GB"))
.ToUniversalTime();
if (_timeZoneInfo.IsInvalidTime(universalFormatDateTime))
Console.WriteLine("Invalid DateTime");
else
Console.WriteLine("Valid DateTime");
You can look at the Convert.ToDateTime articke for future reference.
Upvotes: 0