How to Validate a Datetime in C#

How to Validate a DateTime in C#?

DateTime.TryParse

This I believe is faster and it means you dont have to use ugly try/catches :)

e.g

DateTime temp;
if(DateTime.TryParse(startDateTextBox.Text, out temp))
{
// Yay :)
}
else
{
// Aww.. :(
}

How to validate a DateTime value?

One reason on why ParseExact could fail is when the Day/Month is single digit. So it is better you try

DateTime dateOne = DateTime.ParseExact(firstDate, "d-M-yyyy", 
System.Globalization.CultureInfo.InvariantCulture);

This would ensure it accepts single and double digits for day and month

You can then check if the year is 2018 with DateTime.Year Property

dateOne.Year

Update

Based on your comment, to check if valid date.

if(!DateTime.TryParseExact(firstDate, "d-M-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var dateOne))
{
Console.WriteLine("Not Valid Format");
}

You can also check if the year is 2018 in the same statement.

if(!DateTime.TryParseExact(firstDate, "d-M-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var dateOne) || (dateOne.Year != 2018))
{
Console.WriteLine("Not Valid Format");
}

How to validate DateTime format?

I don't know of any way to actually validate the format they enter since sometimes you want to intentionally include characters that translate into anything. One thing you might consider is allowing the user to self validate by showing a preview of what their entered format translates into.

Best way to validate a date string in C#

The year 201 being invalid is business logic - if you want to have logical safeguards on your imported data (and you should), do them explicitly. With C# you can easily add an extension method to DateTime if you want, something like

public static DateTime ParseDateWithSanity(this DateTime, string date)
{
dt = DateTime.Parse(date);

if dt.Year < 1900
{

throw BadInputException()
}
}

c#: How to parse & validate datetime string that has auto-generated format

This is what tried, you may need additional check to see if the century is sensible in the context of the application you are building

public static void Main()
{
DateTime dt_out;
var style = System.Globalization.DateTimeStyles.None;
var cul = System.Globalization.CultureInfo.CurrentCulture;
//string good_year = "03/01/2009 10:00 AM";
string bad_year = "22/03/202 05:30:01 PM";


// Attempt to convert a string.
if (DateTime.TryParse(bad_year, cul, style, out dt_out))
if(dt_out.Year <= 1900 || dt_out.Year >= 2100)
{
// Date is parsed successfully but not possible in my business context
dt_out = DateTime.MinValue;
Console.WriteLine("Unable to convert {0} to a date and time.", dt_out);
}
else
{
Console.WriteLine("{0} converted to {1} {2}.",dt_out, dt_out, dt_out.Kind);
}
else
Console.WriteLine("Unable to convert {0} to a date and time.", dt_out);
}

Also DateTime is a struct type means it can't be null. From the docs
" The MinValue and MaxValue properties can be used to ensure that a value lies within the supported range before passing it to a DateTime constructor. "
or you can test your own custom date range.
Hope that helps.

C# - Validate an int-based DateTime without exceptions?

The following will check for valid year/month/day combinations in the range supported by DateTime, using a proleptic Gregorian calendar:

public bool IsValidDate(int year, int month, int day)
{
return year >= 1 && year <= 9999
&& month >= 1 && month <= 12
&& day >= 1 && day <= DateTime.DaysInMonth(year, month);
}

If you need to work with other calendar systems, then expand it as follows:

public bool IsValidDate(int year, int month, int day, Calendar cal)
{
return year >= cal.GetYear(cal.MinSupportedDateTime)
&& year <= cal.GetYear(cal.MaxSupportedDateTime)
&& month >= 1 && month <= cal.GetMonthsInYear(year)
&& day >= 1 && day <= cal.GetDaysInMonth(year, month);
}


Related Topics



Leave a reply



Submit