Home > Mobile >  How to return a date or an error? c# .Net
How to return a date or an error? c# .Net

Time:12-14

I am trying to return a date in the format "dd / MM / yyyy" from an entered date. In case the entered date has the following format: "dd-mm-yyyy", I would like to return an error: "The entered date format is not valid." I share my code:

public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        Debug.Assert(typeToConvert == typeof(DateTime));

        return DateTime.ParseExact(reader.GetString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
    }
}

I tried to do the following, but it is not correct because I have to return a DateTime variable:

public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        Debug.Assert(typeToConvert == typeof(DateTime));

        try
        {
            return DateTime.ParseExact(reader.GetString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
        }
        catch (Exception ex)
        {
            var error = "Date format error";
            return error;
        }
    }
}

I hope you can help me! Thanks

CodePudding user response:

In this case, you are implementing JsonConverter<T>, which means the implementation should comply to the expected behaviour of the class, which is throwing JsonException when input value cannot be converted.

public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        Debug.Assert(typeToConvert == typeof(DateTime));

        if (DateTime.TryParseExact(reader.GetString(), "dd/MM/yyyy", 
            CultureInfo.InvariantCulture, DateTimeStyles.None, out var result) 
        {
           return result;
        }
        else throw new JsonException();
    }
}

I use TryParseExact so there's no need to catch exception.

  • Related