Hello everyone!
The LINQ query converts the date from the format “MM/dd/yyyy 00:00:00” to “dd.MM.yyyy”.
It was: 02/12/2022 00:00:00.
It became: 12.02.2022.
But it throws an error if the date cell is empty. Tell me, please, how to make it so that there is no error? Thanks.
Before changing the date type, use an if condition and check if the incoming value is null or not.
Expression: String.IsNullOrEmpty(YourVariable) or String.IsNullOrWhiteSpace(YourVariable)
If true, then the value is empty
If false, in else block use this conversion expression.
(From d In dt_input.AsEnumerable
Let ra= New Object(){
d(0),
If(String.IsNullOrEmpty(d(1).toString),
d(1),
DateTime.ParseExact(d(1).ToString,“MM/dd/yyyy”,System .Globalization.CultureInfo.InvariantCulture).ToString(“dd.MM.yyyy”))
}
Select dt_result.Rows.Add(ra)).CopyToDataTable
Thanks. Is it possible to convert the current LINQ query to TryParse?
dtSample.AsEnumerable().ToList().ForEach(Sub(row) row(“DateCol”)=DateTime.ParseExact(row(“DateCol”).ToString,“MM/dd/yyyy 00:00:00”,System.Globalization.CultureInfo.InvariantCulture).ToString(“dd.MM.yyyy”))
I want to understand how it can be done through TryParse, it seems to me more elegant.
I tried to convert the code, but it doesn’t compile.
dtSample.AsEnumerable().ToList().ForEach(Sub(row) row(“DateCol”)=DateTime.TryParseExact(row(“DateCol”).ToString,“MM/dd/yyyy 00:00:00”,System.Globalization.CultureInfo.InvariantCulture,DateTimeStyles.None).ToString(“dd.MM.yyyy”))
TryParseExact has an additional parameter within the method signature for the returned date, so set this to nothing when not using it or use it
in your usage it is grabing the True/False returned from tryParseExact and will set it as datecol column value. We do assume that this was not your intention
If, for example, the string must not be empty and date format, if so, then we parse, otherwise we do nothing. Wrote an example code, but with errors.
dtSample = dtSample.AsEnumerable.Select(Function(r)
r(0) = If (r(0) IsNot Nothing AndAlso DateTime.DateTime.ParseExact(r(0).ToString,“MM/dd/yyyy 00:00:00”,System.Globalization.CultureInfo.InvariantCulture).ToString(“dd.MM.yyyy”)),
Return r
End Function).CopyToDataTable