bircastri
bircastri

Reputation: 2165

How to validate DateTime

I must validate a DateTime with c#. So I have build this code:

private const string Format = "yyyy-MM-dd hh:mm:ss.fff";
public object ValidDate(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    if (reader.Value == null)
    {
    return null;
    }

    var s = reader.Value.ToString();
    DateTime result;
    if (DateTime.TryParseExact(s, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
    {
    return result;
    }

    return DateTime.Now;
}

Now if I use this date

2016-06-09 11:20:50.125

it is ok, but if I try to use this date

2016-06-09 13:20:50.125

the date not is valide. The problems is on the hour. From 1 to 12 it's ok. From 13 to 24 it isn't ok. How can I fixed it?

Upvotes: 2

Views: 1108

Answers (4)

Soner Gönül
Soner Gönül

Reputation: 98750

hh specifier is for 12-hour clock format which represents the hour as a number from 01 to 12. Use HH specifier instead which is for 24-hour clock format and represents 00 to 23.

private const string Format = "yyyy-MM-dd HH:mm:ss.fff";

Upvotes: 1

Gian Paolo
Gian Paolo

Reputation: 4249

Your format string

yyyy-MM-dd hh:mm:ss.fff

with hh specify you want time expressed in 12 hours Use HH instead of hh and it should work as you expect

Upvotes: 0

Gerald Schneider
Gerald Schneider

Reputation: 17797

The hh in the format you pass to DateTime.TryParseExact() expects an hour in the 12 hour format.

If you have a time in 24 hour format you have to change it to HH:

private const string Format = "yyyy-MM-dd HH:mm:ss.fff";

Upvotes: 1

Marco
Marco

Reputation: 23937

Your format looks off. Replace the hh with HH:

private const string Format = "yyyy-MM-dd HH:mm:ss.fff";

Reference: https://msdn.microsoft.com/en-US/library/8kb3ddd4(v=vs.110).aspx

Upvotes: 4

Related Questions