Convert string to Datetime in LINQ

Asked

Viewed 1,332 times

8

I have a model where all fields are string.

I want to convert to DateTime and Double

For that 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; }
}

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

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

I do this conversion because then I make a query by date order:

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

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

2 answers

9


First, you should only wear one Parse() if you are sure that the format cannot fail. Otherwise you need to use a TryParse(), which would require an auxiliary method if you want to use in LINQ.

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

It seems to me that culture will solve:

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

If not solve, try the parseExact():

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Maybe it’s better to wear one TryParseExact().

Or you might need some variation on this. Formats.

  • so I did it right, what was missing was specifying the date format that Inq is not understanding? the en-US standard should not be default?

  • 1

    LINQ has nothing to do with it. But the format was missing. O default depends on the computer where it is running.

4

I must point out that the form demonstrated by @Maniero is the most indicated. I will just show that there are other ways.

A simple way is to use the Convert.Todatetime. This form will convert 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 on dotNetfiddle.

  • The problem is that Convert.Todatetime on Linq does not work.

  • 1

    @Dorathoto Work works, just look at the example. However, as I said, if you pass a date that it does not accept, it will give error. That’s why I also said that the other answer is the best one. I just posted another way to do it, because you can never have too many.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.