Error formatting date in C#

Asked

Viewed 82 times

1

I’m trying to format a date:

string s = linha.data.ToString("yyyyMMdd");

but I’m getting an error in ToString()

No Overload for Method 'Tostring' takes 1 argument

Any hint?

EDITED

In my date field, when I hover over it, it appears like this: DateTime? bpiUltrassom.data {get; set;}

I don’t know why this interrogation comes up after DateTime

  • But I don’t want to use the strokes, I want the way it is in the code: anomesdia

  • 1

    DateTime? is the guy DateTime that allows Null. See: https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/nullable-types/using-nullable-types

3 answers

1


The question appears because its Datetime property can be null. And a null Datetime does not have the method ToString(String), therefore presents error.

To solve your problem, replace the type of your property DateTime? for DateTime only, or treat its value before conversion and use the .Value. Ex:

string dataFormatada = (data != null? data.Value.ToString("yyyyMMdd") : "");

0

Solution found:

string s = linha.data.Value.ToString("yyyyMMdd");

0

It can be done as follows.

string s = linha.data.ToString().ToString("yyyyMMdd");

Browser other questions tagged

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