Manipulate Date in ASP.NET

Asked

Viewed 69 times

0

I’m starting to learn ASP.NET and can’t find solution to the case below:

I have an instance of Datetime where I do the conversion to "ddMMyyyy" format using Parseexact(), to show the date without mask. The problem is that in Oracle this field is not DATETIME, it is just DATE. When I run the program, I get the error "A cadeia de caracteres não foi reconhecida como valor DateTime válido."

I couldn’t find a Date-only object in ASP.NET to use. Do you have any idea how I can solve this? I didn’t want to have to change the field type in the table.

Follow the code excerpt:

else if (field.TYPECODE == 4)
                        {
                            DateTime _date = DateTime.ParseExact(field.VALUE, "ddMMyyyy", CultureInfo.InvariantCulture);

                            field.VALUE = JsonConvert.SerializeObject(_date);
                        }

1 answer

2

What is happening is that you initially have this date in string, probably received by input, but for some reason you need to work with it deserialized in Datetime, for this you are parse.

The problem is right there, the Parseexact api asks you for the value to be parsed, but it needs to know how to do it so it can work, in case the format.

In order for the parse to occur, the format that the date in string has to correspond exactly with the one of the format informed, otherwise it will not be able to perform, because it will not know the correct format and how to work.

When this happens, he throws an exception with the following feature:

Formatexception: s does not contain a date and time that Corresponds to the Pattern specified in format.

Let’s go to a wrong and correct example:

Wrong:

    ...
    field.VALUE = "10/10/2020";
    var _date = DateTime.ParseExact(field.VALUE, "ddMMyyyy", CultureInfo.InvariantCulture);

It will fail because the formatted date will not match the informed one for it to parse.

-

Right:

    ...
    field.VALUE = "10102020";
    var _date = DateTime.ParseExact(field.VALUE, "ddMMyyyy", CultureInfo.InvariantCulture);

Will return the serialized date in Datetime, because the formatted date matches with the informed format for it to parse.

So your problem is the difference in the format of the date received with which you want the parser to use to deserialize.

For more in-depth information about the api, please visit documentation.

Hugs.

Browser other questions tagged

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