0

I'm trying to convert a Datetime.Now to UTC -11

TimeZoneInfo info = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(x => x.BaseUtcOffset.ToString() == "-11:00:00"); 
 try
 {
     DateTime localTime = DateTime.Now;
     DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(localTime, info);
 }
 catch (Exception ex)
 {
     Console.WriteLine(ex.Message);
 }

The Exception Throwing is: 'The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local. Parameter name: sourceTimeZone'

i'm not founding how to fix it with:

localTime = DateTime.SpecifyKind(localTime, DateTimeKind.Local);

nothing changes

3
  • 3
    Why don't you just use DateTime.UtcNow ?
    – Alex
    Commented May 7 at 21:05
  • 1
    You may want to work with DateTimeOffset instead.
    – gunr2171
    Commented May 7 at 21:46
  • Hi, i end up using DateTime localTime = DateTime.UtcNow; localTime = DateTime.SpecifyKind(localTime, DateTimeKind.Unspecified); DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(localTime, info); to resolve it. Thanks everyone Commented May 8 at 12:35

1 Answer 1

1

Give this a try:

DateTime now = DateTime.Now;
TimeZoneInfo targetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("UTC-11");
DateTime targetTime = TimeZoneInfo.ConvertTime(now, targetTimeZone);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.