The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly

Rahul Kiwitech
Rahul K...
292 Points
26 Posts

I am using  following code to convert datetime to UTC:

scheduledEmail.RegisteredDate = TimeZoneInfo.ConvertTimeToUtc(scheduledEmail.RegisteredDate, tz);

It through compile time exception:

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.

What is Kind property? How I can solved it?

Views: 21759
Total Answered: 3
Total Marked As Answer: 0
Posted On: 03-Apr-2017 22:29

Share:   fb twitter linkedin
Answers
bts
bts
10 Points
0 Posts
         

The DateTime structure supports only two timezones:

  • The local timezone the machine is running in.
  • and UTC.

Have a look at the DateTimeOffset structure.

var info = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");

DateTimeOffset localServerTime = DateTimeOffset.Now;

DateTimeOffset usersTime = TimeZoneInfo.ConvertTime(localServerTime, info);

DateTimeOffset utc = localServerTime.ToUniversalTime();

Console.WriteLine("Local Time: {0}", localServerTime);
Console.WriteLine("User's Time: {0}", usersTime);
Console.WriteLine("UTC: {0}", utc);

Output:

Local Time: 30.08.2009 20:48:17 +02:00
User's Time: 31.08.2009 03:48:17 +09:00
UTC: 30.08.2009 18:48:17 +00:00
Posted On: 05-Apr-2017 05:13
Rahul Kiwitech
Rahul K...
292 Points
26 Posts
         

I solved by following

scheduledEmail.RegisteredDate = 
TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(scheduledEmail.RegisteredDate, DateTimeKind.Unspecified), tz);

But I don't know, why first does not work?

 

Posted On: 05-Apr-2017 05:20
Smith
Smith
2890 Points
78 Posts
         

It depends on how the scheduledEmail.RegisteredDate was originated.

  • If you got it from DateTime.Now, then it will have a Local kind.
  • If you got it from DateTime.UtcNow then it will have an Utc kind.
  • If you got it from new DateTime(2013,5,1) then it will have an Unspecified kind.

It also depends on where you got myTimeZone from. For example:

  • TimeZoneInfo.Local
  • TimeZoneInfo.Utc
  • TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")

The TimeZoneInfo.ConvertTimeToUtc function will only operate if it can match the zone to the kind you give it. If both are local, or both are UTC, then it will work. If you are giving it a specific zone, then the kind should be unspecified.

Posted On: 05-Apr-2017 05:27
 Log In to Chat