Search code examples
c#linqdate-conversion

Convert unusual string to DateTime w/out foreach


Update My Solution:

var rowsToAdd = (from t in dtEntry.AsEnumerable().Cast<DataRow>()
                 let startDate = (
                 t.Field<string>("StartDate").Length > 0)
                     ? DateTime.Parse(t.Field<string>("StartDate").Split(new Char [] {'('})[0], CultureInfo.InvariantCulture)
                     : DateTime.Today.AddMonths(-3)
                 where startDate > filterDate
                 select t);

Original Question: I get a DateTime string from an external API that looks like this:

10/14/2014 8:30 AM (America/Los Angeles)

I have all the data in a datatable called dtEntry which I'm using below.

None of the built-in c# DateTime conversion functions seem to work. They all result in format exeptions. Does anyone know how I could do this? The other catch is that I'm using LINQ (see below).

DataRow[] rows = (from t in dtEntry.AsEnumerable().Cast<DataRow>()
                       let startDate = (
                       t.Field<string>("StartDate").Length > 0)
                           ? DateTime.Parse(t.Field<string>("StartDate"))
                           : DateTime.Today.AddMonths(-3)
                       where startDate > filterDate
                       select t).ToArray();                                       

Any ideas? I've got the ternary operator in there because I need to handle empty strings as well.


Solution

  • You can split your string based on space and then Take(3) elements from the result array, Join them back using string.Join and then use DateTime.ParseExact or DateTime.TryParseExact like:

    string str = "10/14/2014 8:30 AM (America/Los Angeles)";
    string newStr = string.Join(" ", str.Split().Take(3));
    
    DateTime parsingDateTime;
    if (!DateTime.TryParseExact(newStr, "M/d/yyyy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None,
        out parsingDateTime))
    {
        //invalid datetime
    }
    

    EDIT: You have to ignore (America/Los Angeles) part of string, otherwise there is no way for parsing using such string. You can find TimeZone for Region and then create DateTime for that parameter. See this: Get timezone by Country and Region