I am converting date and time from a string. I append the date parts from my input like below
string joinedString = txtMonth.Text.Trim() + "/" + txtDate.Text.Trim() + "/" + txtYear.Text.Trim();
Generally i convert the string like below
DateTime dt;
if (DateTime.TryParse(joinedString, out dt))
{
lblOutputCulture.Text = dt.ToString();
}
else
{
lblOutputCulture.Text = "Invalid Date Time!!!";
}
Here i can get the datetime if the culture and datetime format of the culture is same as my string pattern. But if it is chnaged like 'dd-MM-yy' the conversion shoul failed.
To overcome this, we need to parse using InvariantCulture. For this i found 2 methods
Method 1 : Using DateTime.TryParse
if (DateTime.TryParse(joinedString, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
lblOutput.Text = dt.ToString();
}
else
{
lblOutput.Text = "Invalid Date Time!!!";
}
Here the date time is successfully converted even if the datetime format of the system is changed. Also the following advatages i) The date and month input is 1 digit or 2 digit ii) The year input is 2 digit or 4 digit
Method 2: Using DateTime.TryParseExact
if (DateTime.TryParseExact(joinedString, "M/d/yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
lblOutput.Text = dt.ToString();
}
else
{
lblOutput.Text = "Invalid Date Time!!!";
}
Here also datetime is converted with out culture specific but strict to the format i gave in the tryparseexact statement.
But the following are the issues for this i) If i gave 4 digit year input it shows invalid date and time. If i change the format to 'M/d/yyyy' i can't able to give 2 digit year number. Like if i add time part, i need to give time part mandatory.
So which one is better? Please give a suggestion. But mostly i found the second method in all blogs and forums..
Which one is correct?
I would use neither:
try {
DateTime dt = new DateTime(int.Parse(txtYear.Text),
int.Parse(txtMonth.Text),
int.Parse(txtDate.Text));
lblOutput.Text = dt.ToString(); //Not sure why we'd do this, but whatever
} catch (ArgumentOutOfRangeException) {
lblOutput.Text = "Invalid Date Time!!!";
}
This easily extends to including other parts, e.g. time, by selecting a different overload of the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With