Benk
Benk

Reputation: 1312

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.

Upvotes: 1

Views: 10848

Answers (5)

Deise Vicentin
Deise Vicentin

Reputation: 137

Try the following:

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499760

You're specifying a format of `MM/dd/yyyy hh:mm" but your string isn't in that format even slightly.

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.

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. 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 :(

EDIT: Note that my Noda Time project would allow you to parse the offset part, e.g. 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. 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. Currently Noda Time doesn't have an OffsetDateTime, which would be a natural fit here...

Upvotes: 3

Justin Morgan
Justin Morgan

Reputation: 30695

If you have a look at the Custom Date and Time Format Strings, what you have is just a variant of this format:

"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);

Upvotes: 1

SouthShoreAK
SouthShoreAK

Reputation: 4296

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. 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.

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);
} 

Upvotes: 2

Dave
Dave

Reputation: 359

try ddd MMM d yyyy hh:mm:ss zzz

If it's not working try this

Upvotes: 1

Related Questions