Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use linq for parsing string datetime to real datetime?

my ExpiryDate is "10/31/2015 12:00:00 AM" means MM/dd/YYYY hh:mm:ss AM but it is string from SAP. How can i convert it MM/dd/YYYY below codes not working.error :

"String was not recognized as a valid DateTime."

How can i do that by using linq?

var query = deliveriesItemsbypaging.Select(tb => tb.ExpiryDate)
              .AsEnumerable() // Do the rest of the processing locally
              .Select(x => DateTime.ParseExact(x.Split(new char[0])[0], "MM/dd/yyyy", CultureInfo.InvariantCulture));

this blog code is working :

 var r =   DateTime.ParseExact("10/31/2015 12:00:00 AM".Split(new char[0])[0], "MM/dd/yyyy", CultureInfo.InvariantCulture);
like image 411
ALEXALEXIYEV Avatar asked Dec 24 '22 21:12

ALEXALEXIYEV


1 Answers

You can use DateTime.Parse here

var query = deliveriesItemsbypaging.Select(tb => tb.ExpiryDate)
              .AsEnumerable() // Do the rest of the processing locally
              .Select(x => DateTime.Parse(x, CultureInfo.InvariantCulture).Date);

.Date here will give you date only without time, as you need.

UPDATE: If you want to get an enumerable of strings (in specific format), you might want to rewrite it as

var query = deliveriesItemsbypaging.Select(tb => tb.ExpiryDate)
              .AsEnumerable() // Do the rest of the processing locally
              .Select(x => DateTime.Parse(x, CultureInfo.InvariantCulture).ToString("MM/dd/YYYY"));
like image 84
Heorhiy Pavlovych Avatar answered May 18 '23 19:05

Heorhiy Pavlovych