GMT等于UTC(协调世界时),或多或少(除非你处理的是几分之一秒,没有区别).DateTimeKind是一个枚举,它允许您选择是以本地时区还是以UTC格式显示时间,它内置于 DateTime构造函数中.使用这个,我们可以实现相当于GMT.
我们要使用的构造函数如下:
DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind)
Run Code Online (Sandbox Code Playgroud)
或者(在一个中有一个毫秒的参数,在另一个中则没有):
DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind)
Run Code Online (Sandbox Code Playgroud)
要以UTC格式获取1970年1月1日的DateTime,我们可以使用以下内容:
DateTime inGMT = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); //using 1st constructor above
Run Code Online (Sandbox Code Playgroud)
或者:
DateTime inGMT = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); //using 2nd constructor above
Run Code Online (Sandbox Code Playgroud)
注意:枚举DateTimeKind的内容如下:
更新:Thomas Levesque在他的回答中提出了一个非常有创意的解决方案,但我不确定它是否是最直接的方法,如果它是一种可用于任何时区的可行方法.我认为他说的是,你可以计算的DateTimeOffset从DateTime.Now和DateTime.UtcNow,并应用在自己的时区,它给你它UTC/GMT时间算出偏移至1970年1月1日.我不确定是否有简单的方法来计算其他时区的偏移量,然后这个问题变得有点多余.
更新#2:我添加了另一个DateTime构造函数,它完成了同样的事情,但缺少毫秒参数.它们是可互换的.