Convert string to DateTime in LINQ

6

I have a model where all fields are string .

I want to convert to DateTime and Double

For this I created a new model

public class CPUStats
{
    public DateTime Data { get; set; }
    public Double? Disco { get; set; }
    public Double? CPU { get; set; }
    public Double? RAM { get; set; }
}

I made this select:

  var DateQuery = db.servidorSQL.ToList().Select(o => new CPUStats
            {
                Data = DateTime.Parse(o.Data),
                CPU = Double.Parse(o.CPU),
                RAM = Double.Parse(o.RAM),
                Disco = Double.Parse(o.Disco)
            });

But I get the error:

  

String was not recognized as a valid DateTime.

in line: var DateQuery = db.servidorIIS.ToList().Select(o => new CPUStats

I make this conversion because then I make a query in order of date:

 var CPU = DateQuery.OrderByDescending(x => x.Data).Take(5).ToList();

In MSSQL this date field that is string has the following data: 03/16/2016 04: 09: 16.936

    
asked by anonymous 16.03.2016 / 14:41

2 answers

9

First, you should only use Parse() if you are sure that the format can not fail. Otherwise you must use a TryParse() , which would require an auxiliary method if you want to use it in LINQ.

If you can ensure that the format is this, you can use the culture or customize the expected format for the parser .

I think culture will solve:

DateTime.Parse(o.Data, new CultureInfo("en-US"));

If this does not resolve, try parseExact() :

DateTime.ParseExact(o.Data, "MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

See working on dotNetFiddle .

Maybe it's still better to use a TryParseExact() .

Or you may need some variation from this. Formats .

    
16.03.2016 / 15:01
2
  

I should point out that the form shown by @bigown is the most appropriate one. I'll just show that there are other ways.

A simple way is to use Convert.ToDateTime. This will do the value. However, if the value is not a valid date, it will give error.

An example would be:

var stringData =  "06/20/2016";

var stringDataConvertida = Convert.ToDateTime(stringData);

Console.WriteLine(stringDataConvertida);

See the functional example in dotNetfiddle.

    
20.06.2016 / 16:51