Check several date formats using DateTime.TryParse() - c#

I'm using a method to validate textboxes.
public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes)
{
DateTime value = DateTime.Today;
//string dateFormat = "dd/mm/yyyy";
foreach (var textBox in textBoxes)
{
if (!DateTime.TryParse(textBox.Text, out value))
{
return false;
}
}
return true;
}
I want to check the format too. It requires mm/dd/yyyy, but want it to be dd/mm/yyyy

Try DateTime.TryParseExact
DateTime dt;
DateTime.TryParseExact(textBox.Text,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
If you want to check multiple formats as you updated in your question then you can do using another overload method of TryParseExact which takes format parameter as array of string.
string[] formats = { "dd/MM/yyyy", "MM/dd/yyyy" };
DateTime.TryParseExact(txtBox.Text,
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out value));
Please take care of format string. As you have mentioned format as dd/mm/yyyy. Here mm represents the minute not the month. Use MM for the month representation.

DateTime.TryParseExact(textBox.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out outDt))

public bool ValidateDateTimeTextBoxes(params TextBox[] textBoxes)
{
DateTime value = DateTime.Now;
//string dateFormat = "dd/mm/yyyy";
foreach (var textBox in textBoxes)
{
if (!DateTime.TryParse(textBox.Text,"dd/mm/yyyy",new CultureInfo("en-US"),
DateTimeStyles.None out value))
{
return false;
}
}
return true;
}

Try using TryParseExact
Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly. The method returns a value that indicates whether the conversion succeeded.
DateTime.TryParseExact(DateValue,
"dd/mm/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out outDatetime);

Use TryParseExact instead which is also faster.
Example:
using System;
using System.Globalization;
class Program
{
static void Main()
{
string dateString = "27/05/2012"; // <-- Valid
string dtformat = "dd/mm/yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, dtformat, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
{
Console.WriteLine(dateTime);
}
}
}

Related

Parse DateTime with and without leading zeros

I have a TextBox in which the user can type a date. I only expect following formats:
12.12.2017
12.02.2017
12.2.2017
02.12.2017
2.12.2017
02.02.2017
2.2.2017
So there can be a leading zero or not.
I am currently parsing the DateTime with following code:
DateTime myDate = new DateTime();
bool success = DateTime.TryParseExact(TboDate.Text, "dd.MM.yyyy",
CultureInfo.CurrentUICulture, DateTimeStyles.None, out myDate);
Dates like 12.2.2017 can not be parsed successfully with that code. But I don't want to check the string everytime and parse it then with the matching format d.M.yyyy, dd.M.yyyy, d.MM.yyyy and so on. Is there an easier way to tell the method, that there can be leading zeros?
They could all be parsed without a problem with Parse/TryParse f.e. with de-DE culture:
var dates = new[] { "12.12.2017", "12.02.2017", "12.2.2017", "02.12.2017", "2.12.2017", "02.02.2017", "2.2.2017" };
foreach (var dateStr in dates)
{
DateTime dt;
if (!DateTime.TryParse(dateStr, CultureInfo.CurrentUICulture, DateTimeStyles.None, out dt))
{
Console.WriteLine("not valid: " + dateStr);
}
}
But you could also use ParseExact if you specify all allowed formats:
string[] allowedFormats = { "dd.MM.yyyy", "d.MM.yyyy", "dd.M.yyyy", "d.M.yyyy" };
foreach (var dateStr in dates)
{
DateTime dt;
if (!DateTime.TryParseExact(dateStr, allowedFormats, CultureInfo.CurrentUICulture, DateTimeStyles.None, out dt))
{
Console.WriteLine("not valid: " + dateStr);
}
}
Update
As Jon Skeet has mentioned it's not necessary to specify multiple, this handles all: "d.M.yyyy"

How to compare date values In dataGrid with current date?

I have tried with
protected void gridCustomer_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime olddate = Convert.ToDateTime(e.Row.Cells[9].Text);
// Error : String was not recognized as a valid DateTime./ 'DateTime today = DateTime.Now;'
if (olddate > today)
{
Label status = (Label) e.Row.FindControl("lblStatus");
status.Text = "AutoHold";
}
}
}
Convert.ToDateTime method uses your CurrentCulture settings by default if you don't provide any IFormatProvider as a second parameter.
That means, your CurrentCulture doesn't have yyyy-MM-dd as a standard date and time format.
In such a case, you can specify your string format with DateTime.TryParseExact or DateTime.ParseExact methods like;
DateTime olddate;
if(DateTime.TryParseExact(e.Row.Cells[9].Text, "yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out olddate))
{
// Your olddate will be 28/03/2015 00:00:00
}
but in old date getting '1/1/0001' where as in my grid cell i have
'4/1/2015' by above your mentioned code.
Clearly, your 4/1/2015 doesn't match with yyyy-MM-dd format, that why your olddate will be the default value of DateTime which is DateTime.MinValue (1/1/0001).
If your string can be more than one format, DateTime.TryParseExact has an overload that takes formats as a string array. With that, you can specify all possible formats your string.
For example;
string s = "4/1/2015";
DateTime dt;
var formats = new string[]{"yyyy-MM-dd", "M/d/yyyy"};
if(DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// Your dt will be 01/04/2015 00:00:00
}
use:
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "2015-03-28";
format = "yyyy-MM-dd";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
MSDN
Replace this line in code
DateTime olddate = DateTime.ParseExact(e.Row.Cells[9].Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Convert.ToDateTime will throw exception if there is a difference in current culture and the format of date time string
Use DateTime.ParseExact
string res = "2012-07-08";
DateTime d = DateTime.ParseExact(res, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy")); // can set any format

String to date parsing error "String was not recognized as a valid DateTime."

In my property below I m parsing string to datetime.
public virtual string StartTimeLocal
{
set { StartTime = DateTime.Parse(value).ToUTCDateTime(); }
}
Just checked in value I have 26/1/2014 02:17 PM
Can you please help me what wrong I m doing and how to correct it ?
DateTime.Parse parses standart date and time formats. Your string is not one of them.
You can use DateTime.TryParseExact or DateTime.ParseExact methods instead.
string s = "26/1/2014 02:17 PM";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/M/yyyy hh:mm tt",
CultureInfo.GetCultureInfo("en-US"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
else
{
//Your string is not a valid DateTime.
}
Your input is formatted using en-US culture settings, so you should either make sure your application runs on system with local culture set to en-US or specify culture explicitly:
public virtual string StartTimeLocal
{
set { StartTime = DateTime.Parse(value, CultureInfo.GetCultureInfo("en-US")).ToUTCDateTime(); }
}
Try the below:
CultureInfo provider = CultureInfo.InvariantCulture;
format = "dd/MM/yyyy hh:mm tt";
result = DateTime.ParseExact(dateString, format, provider);

String based DateTime format or pattern check

I have a datetime string.
string strDate = "20140424_18255375";
How to verify the datetime is having in this format YYYYMMDD_HHmmssff
I tried:
bool isTrue = DateTime.TryParseExact(strDate, "YYYYMMDD_HHmmssff", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Please help if there is a better way to verify the datetimes with RegEx or any normal way.
Using TryParseExact is the right way to go about it, but you need to use the right format specifiers. In this case, I think you want:
bool valid = DateTime.TryParseExact(strDate, "yyyyMMdd_HHmmssff",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
Note the use of yyyy instead of YYYY and dd instead of DD. Format specifiers are case-sensitive.
Try this
public override bool IsValid(object value)
{
var dateString = value as string;
if (string.IsNullOrWhiteSpace(dateString))
{
return true; // Not our problem
}
DateTime result;
var success = DateTime.TryParse(dateString, out result);
return success;
}
just add your format for date.

Better way to Select & Read Date in dd/mm/yy format?

In earlier vb.net 2008 I used the DateTime to read the date in dd/mm/yy format.
I use to change the culture info to UK format. So that the date will be selected from SQL server as in dd/mm/yy format.
But I know it's not good to play with CultureInfo. Even though I used like the following manner.
Any other better Ideas for me?
Sub Form_Load()
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-GB", False)
End Sub
Any other better Ideas for me? Thanks for the Ideas.
Thanks & Regards.
From DateTime to string:
string s = DateTime.Today.ToString("dd/MM/yyyy");
From string to DateTime:
DateTime d;
bool success = DateTime.TryParseExact("26/05/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
In C# you could get the date string in desired format like,
string date = DateTime.Now.ToString("dd/MM/yyyy");
If you want to get DateTime object from string value representing DateTime in specific culture, you can do
DateTime dt = new DateTime();
DateTime.TryParse("16/01/2011", System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"),
System.Globalization.DateTimeStyles.None, out dt);
DateTime --> String
DateTime.Now.ToString( new CultureInfo("fr-FR", false) );
String --> DateTime:
The preferred method would probably be DateTime.Parse()
dateString = "16/02/2008 12:15:12";
try
{
dateValue = DateTime.Parse(dateString, new CultureInfo("en-GB", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
This way you are not changing the Culture info of the current Context. This does assume you know what the format will be beforehand though.
You can format the date using the CultureInfo, without setting the culture for the whole thread, thanks to the IFormatProvider interface:
DateTime d = DateTime.Now;
CultureInfo c = new CultureInfo("en-GB", false);
string s = d.ToString(c.DateTimeFormat);
This has the added advantage that you don't have any hard-coded formats, and if the user changes the localisation settings on their machine, your application will reflect their preferences.
You can use DateTime.TryParse to parse the date...
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}
And even use an IFormatProvider to help TryParse work out the format.
CultureInfo c = new CultureInfo("en-GB", false);
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, c.DateTimeFormat, DateTimeStyles.None, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}

Categories

Resources