简体   繁体   English

如何在给定 UTC 时间和日期的情况下创建 DateTime 对象?

[英]How do I create a DateTime object given UTC time and date?

I have date and time strings already in UTC.我已经有 UTC 格式的日期和时间字符串。 I need to use those strings to create a DateTime object.我需要使用这些字符串来创建一个 DateTime 对象。

This is the code I'm using.这是我正在使用的代码。 The problem is the time gets converted and my UTC time on the datetime object is no longer correct.问题是时间被转换了,我在 datetime 对象上的 UTC 时间不再正确。 I'm giving UTC values so they shouldn't get converted again.我给出了 UTC 值,所以它们不应该再次被转换。

string format = $"{dateFormat}_{timeFormat}";
string value = $"{dateValue}_{timeValue}";

var x = DateTimeOffset.ParseExact(value, format, CultureInfo.CurrentCulture).UtcDateTime;

where dateFormat = "ddMMyy" , timeFormat = "HHmmss" , dateValue = "191194" and timeValue = "225446".其中dateFormat = "ddMMyy"timeFormat = "HHmmss"dateValue = "191194"timeValue = "225446".

D Stanley's answer certainly works, but is slightly more complex than you need - if you want a DateTime as the result, you don't need to use DateTimeOffset at all, as DateTime.ParseExact handles DateTimeStyles.AssumeUniversal as well, although you need to specify AdjustToUniversal so that the result is in UTC. D Stanley 的答案当然有效,但比您需要的稍微复杂一些 - 如果您想要一个DateTime作为结果,您根本不需要使用DateTimeOffset ,因为DateTime.ParseExact处理DateTimeStyles.AssumeUniversal ,尽管您需要指定AdjustToUniversal以便结果采用 UTC。 (Otherwise it's adjusted to the local time zone automatically - and unhelpfully, IMO, but that's a battle for another day.) (否则它会自动调整为本地时区 - 并且无益,IMO,但这是另一天的战斗。)

var x = DateTime.ParseExact(
     value, 
     format, 
     CultureInfo.CurrentCulture,  
     DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

Sample code (that revealed to me the need for DateTimeStyles.AdjustToUniversal ):示例代码(向我表明需要DateTimeStyles.AdjustToUniversal ):

using System;
using System.Globalization;

class Test
{
    static void Main(string[] args)
    {
        string text = "2015-06-10 20:52:13";        
        string format = "yyyy-MM-dd HH:mm:ss";
        var dateTime = DateTime.ParseExact(
            text,
            format, 
            CultureInfo.InvariantCulture,
            DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
        Console.WriteLine(dateTime);  // 10/06/2015 20:52:13 on my box
        Console.WriteLine(dateTime.Kind); // Utc
    }
}

I'd be careful using CultureInfo.CurrentCulture , by the way - bare in mind the fact that it can affect the calendar system in use as well as format strings etc.顺便说一下,我会小心使用CultureInfo.CurrentCulture - 请记住它会影响正在使用的日历系统以及格式字符串等。

(As a side-note of course, I'd recommend using my Noda Time library instead. In this case I'd probably suggest parsing your time using a LocalTimeFormat , your date using a LocalDateFormat , then adding the results together to get a LocalDateTime that you could then convert to a ZonedDateTime using UTC. Or you could use your existing approach to create a ZonedDateTimePattern or InstantPattern , of course.) (当然,作为旁注,我建议改用我的Noda Time库。在这种情况下,我可能建议使用LocalTimeFormat解析您的时间,使用LocalDateFormat解析您的日期,然后将结果加在一起以获得LocalDateTime然后您可以使用 UTC 转换为ZonedDateTime 。当然,您也可以使用现有方法创建ZonedDateTimePatternInstantPattern 。)

Use the overload of DateTimeOffset.ParseExact that takes a DateTimeStyles value:使用采用DateTimeStyles值的DateTimeOffset.ParseExact的重载:

var x = DateTimeOffset.ParseExact(value, 
                                  format, 
                                  CultureInfo.CurrentCulture,  
                                  DateTimeStyles.AssumeUniversal)
                      .UtcDateTime;

Note that the call to UtcDateTime doesn't hurt anything, but the time will already be in UTC time (which is what you want) so it will give you back the equivalent DateTime value.请注意,对UtcDateTime的调用不会造成任何伤害,但时间已经是 UTC 时间(这是您想要的),因此它将返回等效的DateTime值。 You can just use DateTime.ParseExact as Jon suggests, which has the same overload.您可以像 Jon 建议的那样使用DateTime.ParseExact ,它具有相同的重载。

This solution also will be helpful if you have your date not as one string.如果您的日期不是一个字符串,此解决方案也将有所帮助。 Just use DateTimeKind.Utc as constructor parameter of DateTime :只要使用DateTimeKind.Utc作为构造函数参数DateTime

new DateTime(2020, 05, 07, 18, 33, 0, DateTimeKind.Utc);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取DateTime对象,给定本地时间作为字符串,日期作为UTC DateTime和时区语言环境字符串? - Get DateTime object given local time as string, date as UTC DateTime and a timezone-locale string? 给定一个 DateTime 对象,如何以字符串格式获取 ISO 8601 日期? - Given a DateTime object, how do I get an ISO 8601 date in string format? 给定DayOfTheWeek我如何从现有日期时间中获取日期 - Given a DayOfTheWeek how do i get the date from an existing datetime 如何在 JavaScript 中将本地日期(没有时间)转换为 UTC DateTime - How to convert local date (without time) in UTC DateTime in JavaScript 当存储为UTC时,如何全局序列化和反序列化Date vs DateTime? - How do I globally serialize and deserialize Date vs DateTime when stored as UTC? 如何从 Utc 日期时间 object 和时区偏移值获取时区信息 - How can I get time zone information from Utc date time object and timezone offset value UTC是否有任何功能可以将特定日期时间转换为UTC日期时间 - Is there any function for UTC to convert to particular datetime to UTC date time 如何将这个特殊的日期和时间解析为DateTime? - How do i parse this special date and time to a DateTime? 如何从DateTime字符串中检索日期和时间 - How do I retrieve the date and time from DateTime string 如何创建一个倒计时到给定时间和日期的计数器? - How can I create a counter that counts down to a given time and date?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM