简体   繁体   English

如何将字符串转换为日期时间

[英]How to convert string to date time

 string value =     "Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)"

I need to convert to date time 我需要转换为日期时间

I tried doing: 我试着做:

 DateTime datetime = DateTime.ParseExact(value, "MM/dd/yyyy hh:mm", null);

or 要么

 DateTime datetime2 = Convert.ToDateTime(value);

Exception: String was not recognized as a valid DateTime. 例外:字符串未被识别为有效的DateTime。

You're specifying a format of `MM/dd/yyyy hh:mm" but your string isn't in that format even slightly . 您指定的格式为“ MM / dd / yyyy hh:mm”,但字符串的格式甚至略有不同

I suspect you'll have trouble with the "GMT-0400 (Eastern Daylight Time)" part - the rest is in a format of "ddd MMM dd yyyy HH:mm:ss" or "ddd MMM d yyyy HH:mm:ss" if the day-of-month number isn't always two digits. 我怀疑您在使用“ GMT-0400(东部夏令时间)”时会遇到麻烦-其余部分的格式为“ ddd MMM dd yyyy HH:mm:ss”或“ ddd MMM d yyyy HH:mm:ss” ”,如果月份中的日期并非总是两位数。

I suggest you parse the offset from UTC separately, and create a DateTimeOffset - parse the first part (before GMT) as an unspecified DateTime - and then parse the offset. 我建议您分别从UTC解析偏移量,并创建一个DateTimeOffset将第一部分(在GMT之前)解析为未指定的 DateTime然后解析该偏移量。 EDIT: You can parse the offset with TimeSpan.ParseExact but you'll need to handle the sign yourself, I believe - I can't see any documented way of parsing a negative timespan that way :( 编辑:您可以使用TimeSpan.ParseExact解析偏移量,但您需要自己处理符号,我相信-我看不到有任何记录这种方式来解析负时间跨度的方法:(

EDIT: Note that my Noda Time project would allow you to parse the offset part, eg with a pattern of "'GMT'+HHmm" - and obviously we'd cope with the LocalDateTime part - but you'd still need to separate the different parts of the string from each other. 编辑:请注意,我的Noda Time项目允许您解析偏移量部分,例如使用“'GMT'+ HHmm”模式-显然我们会处理LocalDateTime部分-但您仍然需要分开字符串的不同部分。 Sample code: 样例代码:

using System;
using System.Linq;
using System.Xml.Linq;
using NodaTime;
using NodaTime.Text;

public class Test
{
    static void Main()
    {
        string text = "Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)";
        ZonedDateTime parsed = Parse(text);
        Console.WriteLine(parsed);
    }

    static readonly LocalDateTimePattern LocalPattern =
        LocalDateTimePattern.CreateWithInvariantInfo("ddd MMM d yyyy HH:mm:ss");

    // Note: Includes space before GMT for convenience later
    static readonly OffsetPattern OffsetPattern =
        OffsetPattern.CreateWithInvariantInfo("' GMT'+HHmm");

    static ZonedDateTime Parse(string text)
    {
        int gmtIndex = text.IndexOf(" GMT");
        int zoneIndex = text.IndexOf(" (");
        // TODO: Validation that these aren't -1 :)

        string localText = text.Substring(0, gmtIndex);
        string offsetText = text.Substring(gmtIndex, zoneIndex - gmtIndex);

        var localResult = LocalPattern.Parse(localText);
        var offsetResult = OffsetPattern.Parse(offsetText);

        // TODO: Validate that both are successful

        var fixedZone = DateTimeZone.ForOffset(offsetResult.Value);        
        return localResult.Value.InZoneStrictly(fixedZone);
    }
}

Note that this will give a ZonedDateTime in a fixed time zone - not really Eastern time. 请注意,这将在固定时区(不是真正的东部时间)中给出ZonedDateTime Currently Noda Time doesn't have an OffsetDateTime , which would be a natural fit here... 目前Noda Time没有OffsetDateTime ,这在这里很自然。

请尝试以下操作:

Convert.ToDateTime("Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)".Substring(4, 20))

Your string doesn't match your format. 您的字符串与您的格式不匹配。

You need to parse that string a bit before trying to convert it. 您需要先分析该字符串,然后再尝试对其进行转换。 For example, "Apr 28 2012 11:00:00" could be parsed. 例如,可以解析“ Apr 28 2012 11:00:00”。 But, you'll need to convert the rest of it yourself. 但是,您需要自己转换其余部分。

You may want to look into using DateTimeOffset documented here , because it can hold time relative to UTC, like your string. 您可能想研究使用此处记录的 DateTimeOffset ,因为它可以保存相对于UTC的时间,例如您的字符串。

Found this is the documentation, pretty close to what you have 发现这是文档,与您所拥有的非常接近

// Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try
{
    result = DateTimeOffset.ParseExact(dateString, format, provider);
    Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
} 

try ddd MMM d yyyy hh:mm:ss zzz 尝试ddd MMM d yyyy hh:mm:ss zzz

If it's not working try this 如果不起作用,请尝试

If you have a look at the Custom Date and Time Format Strings , what you have is just a variant of this format: 如果您查看Custom Date and Time Format Strings ,那么您所得到的只是该格式的一种变体:

"ddd MMM dd yyyy h:mm:ss zzz"

Only there are some extra pieces in it: 里面只有一些额外的部分:

"ddd MMM dd yyyy h:mm:ss GMTzzz (blah blah blah)"

If you deal with those, you should be fine: 如果您处理这些问题,应该没问题:

value = value.Remove(value.IndexOf(" ("));
DateTime datetime = DateTime.ParseExact(value, "ddd MMM dd yyyy hh:mm:ss \"GMT\"zzz", null);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM