How to convert DateTime of type DateTimeKind.Unspecified to DateTime.Kind.Utc in C# (.NET)

邮差的信 提交于 2019-12-01 02:07:28

Do you maybe need something like this:

var unspecified = new DateTime(2016, 12, 12, 10, 10, 10, DateTimeKind.Unspecified);
var specified = DateTime.SpecifyKind(unspecified, DateTimeKind.Utc);

About SpecifyKind() method from MSDN:

The SpecifyKind method creates a new DateTime object using the specified kind parameter and the original time value.

It will create new object, new Kind and same time value. You cannot change Kind of existing object, you need to create new one with same values and different Kind.

Regarding to other question here are supported types in SQL Compact. And here is issue regarding to DateTimeOffset. It looks like that it is not supported yet in Sql Compact.

I use an extension method:

public static DateTime SetKind(this DateTime DT, DateTimeKind DTKind)
{        
    var NewDT = New DateTime(DT.Year, DT.Month, DT.Day, DT.Hour, DT.Minute, DT.Second, DT.Millisecond, DTKind);
    Return NewDT;
}

This is much shorter to use in LINQ than having to type out DateTime.SpecifyKind(unspecified, DateTimeKind.Utc) every time.

For example:

table.Where((x) x.StartTimeStampUTC.SetKind(DateTimeKind.Utc).ToString("G") = GUIStartTimeStampTxt.Text)

You could combine the two above answers for a cleaner solution...

public static DateTime SetKind(this DateTime DT, DateTimeKind DTKind)
{        
    return DateTime.SpecifyKind(DT, DTKind);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!