DateTime.TryParseExact() rejecting valid formats - c#

I'm parsing a DateTime value in an ASP.NET WebForms page and the date string keeps getting rejected by the DateTime.TryParseExact() method even though it clearly matches one of the supplied format strings.
It seems to fail on my development machine at home but work on the production server, so I am thinking of local date settings being involved, but this error occurs even when I supply an IFormatProvider (CultureInfo) object as a parameter
Here's the code:
DateTime startDate;
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
"dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy"};
var errStart = row.FindControl("errStartDate"); //my date format error message
if (!DateTime.TryParseExact(txtStartDate.Text, formats, null, DateTimeStyles.None, out startDate))
{
errStart.Visible = true; //we get here even with a string like "20/08/2012"
return false;
}
else
{
errStart.Visible = false;
}
Note I'm giving a null FormatProvider in the above, but the same problem occurs when I provide a CultureInfo object as
(CultureInfo provider = new CultureInfo("en-US")) for this parameter.
What am I missing?

Try:
DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate)

Here you can check for couple of things.
Date formats you are using correctly. You can provide more than one format for DateTime.TryParseExact. Check the complete list of formats, available here.
CultureInfo.InvariantCulture which is more likely add problem. So instead of passing a NULL value or setting it to CultureInfo provider = new CultureInfo("en-US"), you may write it like.
.
if (!DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate))
{
//your condition fail code goes here
return false;
}
else
{
//success code
}

This is the Simple method, Use ParseExact
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result;
String dateString = "Sun 08 Jun 2013 8:30 AM -06:00";
String format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);
This should work for you.

Try C# 7.0
var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
? dt : DateTime.Parse("1800-01-01");

string DemoLimit = "02/28/2018";
string pattern = "MM/dd/yyyy";
CultureInfo enUS = new CultureInfo("en-US");
DateTime.TryParseExact(DemoLimit, pattern, enUS,
DateTimeStyles.AdjustToUniversal, out datelimit);
For more https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx

Related

date to be converted to UK date format with preserving 0's

I want my date to be converted to UK date format.
so example if its 26/2/2016 then it should be converted to 26/02/2016.
if its a 2/13/2016 then it should be converted to 13/02/2016.
The end result should be UK format with preserving 0 in day and month.
Code
string cellvalue;
string oData = "2/13/2016";
if (DateTime.TryParse((string)oData, CultureInfo.CurrentUICulture, styles, out dt))
{
cellvalue = dt.ToString("dd/MM/yyyy");
Console.WriteLine(cellvalue + "go to hell");
}
else
{
cellvalue = oData.ToString();
Console.WriteLine(cellvalue + "go to bokaro");
}
Easyyy:
CultureInfo enGB = new CultureInfo("en-GB");
string oData = "2/13/2016";
DateTime dateValue;
// Parse date with no style flags.
dateString = "13/02/2016";
DateTime.TryParseExact(oData, "g", enGB, DateTimeStyles.None, out dateValue);
As far as I understand you want resulting date to be in default UK format i.e. dd/MM/yyyy no matter if input date string is in MM/dd/yyyy or dd/MM/yyyy, former being default format for US dates.
You were close in the code you have already tried. Additionally you need to one thing - if input is in US format, parse it as DateTime using US culture, and then simply transform to UK.
var UKCulture = new CultureInfo("en-GB");
var USCulture = new CultureInfo("en-US");
DateTime dt;
string cellvalue;
string oData = "13/2/2016";
// First try parsing to UK format
if (!DateTime.TryParse(oData, UKCulture, DateTimeStyles.None, out dt))
{
// If fails, then try US format
DateTime.TryParse(oData, USCulture, DateTimeStyles.None, out dt);
}
// Once you have DateTime instance, you can do anything. Parsing is over.
cellvalue = dt.ToString("dd/MM/yyyy");
Console.Write(cellvalue);
So now this gives final value as 13/02/2016 for both 2/13/2016 and 13/2/2016 inputs.

String was not recognized as a valid DateTime. Throws an Exception

I'm trying to convert current date to a specified format.
DateTime date = DateTime.ParseExact(DateTime.Now.ToString(), "yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
I'm receiving the following exception.
String was not recognized as a valid DateTime.
My local TimeZone is (UTC+10:00)Melbourne.
What am I doing wrong here?
Your code (even if it worked), would do nothing. It would simply serialize and deserialize the date. I believe you're looking for this:
string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
It doesn't work because DateTime.Now.ToString() is giving a string like (I happen to be in the same timezone, and presumably have the same culture as you):
14/01/2016 3:54:01 PM
Which is of the format:
dd/MM/yyyy h:mm:ss tt
Which does not match the format you're using: yyyy-MM-dd HH:mm:ss.fff
Try this:
string fm = "yyyy-MM-dd HH:mm:ss.fff";
string str = DateTime.Now.ToString(fm, CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(str, fm, CultureInfo.InvariantCulture);
EDIT:
A better way to achieve the date in the format would be like
DateTime now = DateTime.Now;
CultureInfo culture = new CultureInfo("en-AU"); //Melbourne
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
IDEONE DEMO

ASP.NET MVC - Date and time string validation

I'm using ASP.NET MVC and the application user will be able to encode a date with time. I'm wondering if I should use the DateTime.TryParse function to determine if it is a valid date time string or if I should use a Regular Expression in my ViewModel.
In case of using a Regex, is there any existing Date and Time regex? Because I didn't find one in the dd/MM/yyyy hh:mm:ss format.
EDIT : I've decided to use the TryParseExact and check if the encoded date and time is valid.
The dates entered are 15/10/2014 13:00 and 15/10/2014 15:00
Here's what I'm doing :
DateTime dtS;
DateTime dtE;
DateTimeFormatInfo fmt = (new CultureInfo("fr-FR")).DateTimeFormat;
bool validStart = DateTime.TryParseExact(svm.StartApp, "dd/MM/yyyy HH:mm:ss", fmt, DateTimeStyles.None, out dtS);
bool validEnd = DateTime.TryParseExact(svm.EndApp, "dd/MM/yyyy HH:mm:ss", fmt, DateTimeStyles.None, out dtE);
if (!validStart || !validEnd)
{
return RedirectToAction("Index");
}
My bool variables are getting the false value and I cannot see why. Any idea?
Your error was in trying to get seconds. You have not seconds in your string.
Now is working:
DateTime dtS;
DateTime dtE;
bool validStart = DateTime.TryParseExact("15/10/2014 13:00", "dd/MM/yyyy HH:mm", new CultureInfo("fr-FR"), DateTimeStyles.None, out dtS);
bool validEnd = DateTime.TryParseExact("15/10/2014 13:00", "dd/MM/yyyy HH:mm", new CultureInfo("fr-FR"), DateTimeStyles.None, out dtE);

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);

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