C#将DateTimeKind应用于DateTime对象

时间:2017-12-29 15:27:03

标签: c# datetime

鉴于DateTime.Kind是一个只用属性,我们如何将DateTimeKind分配给DateTime.Parse()生成的DateTime对象?

var dte = DateTime.Parse("01/01/2018 10:10:00");

Console.WriteLine("{0} | Kind: {1}", dte, dte.Kind.ToString());

// PRINTS: 1/1/2018 10:10:00 AM | Kind: Unspecified

dte = dte.ToLocalTime();

Console.WriteLine("{0} | Kind: {1}", dte, dte.Kind.ToString());

// PRINTS: 1/1/2018 6:10:00 PM | Kind: Local
// OK, the "Kind" is changed to "Local" which is what I'm trying to achieve 
// however it also converted the time!!!

我的问题是如何申请Utc或Local" Kind"不使用dte.ToUniversal()或dte.ToLocal()到对象dte,因为两个方法都转换(或更改)时间

1 个答案:

答案 0 :(得分:1)

您应该能够使用所需的DateTimeKind创建一个新的DateTime,使用解析的日期时间和一个采用DateTimeKind的构造函数,如下所示:
msdn.microsoft.com/en-us/library/t882fzc6(v=vs.110).aspx