DateTime.TryParse for any culture - c#

There are lots of thread for this , but I am still blocked at the following:
What I have:
I am trying to build windows phone App which will pick Date of Birth of an individual
Code Behind:
string dateString = "";
DateTime dt = DateTime.Now;
if (value != null && DateTime.TryParse(value.ToString(), culture, DateTimeStyles.None, out dt))
{
if (dt.Equals(DateTime.MinValue))
{
//dateString = "mm/dd/yyyy";
return "";
}
else
return dt.ToShortDateString();
}
else
return dateString;
}
what I need:
I want it to parse any date format which should be culture Independent.
What I tried:
1.I tried using CultureInfo.InvariantCultute, CultureInfo.CurrentCulture
2.Tried using ExactParser as follows:
string[] formats = {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", "d/M/yyyy hh:mm:ss tt", "dd/MM/yyyy hh:mm:ss tt", "d/M/yyyy" , "dd/MM/yyyy" , "M/d/yyyy" ,"MM/dd/yyyy",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", "dd/MM/yyyy hh:mm:ss", "d/M/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", "d/M/yyyy hh:mm tt", "d/M/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm", "d/M/yyyy h:mm", "d/M/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm","dd/MM/yyyy hh:mm", "dd/M/yyyy hh:mm"};
if (value != null && DateTime.TryParseExact(value.ToString(), format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
but that is too hardcoded and will not cover several cases.
Is there any way to pick DOB in any format?
Any help would be Appreciated. Thanks!!

Not really, because everyone has their own date formatting.
What you're basically trying to do is magically deduce the dates from the second half of the above XKCD comic. ;)
That said, the only way you could TRY and do this, is to parse a string with every format you think it might be, and then make a sanity check in every case where a parse was successful. Said sanity check would be difficult however... Does 11-02 mean February 11th or November 2nd? You'd require some sort of context.

Sorry, but it seems impossible, since datetime could be ambiguous, and that's why misinterpreted e.g.
"01/02/03" is
01 Feb 2003 (Russia)
02 Jan 2003 (USA)
03 Feb 2001 (China)
see http://en.wikipedia.org/wiki/Date_format_by_country

This will try all culture:
public static bool TryParseAnyDate(string dateValue, out DateTime result)
{
result = DateTime.MinValue;
foreach (CultureInfo cultureInfo in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
if (DateTime.TryParse(dateValue, cultureInfo, DateTimeStyles.None, out result))
{
return true;
}
}
return false;
}

Related

Convert dd/MM/yyyy HH:mm tt to MM/dd/yyyy HH:mm tt in C#

I want to convert string as : "25/12/2017 4:00 PM" to "12/25/2017 4:00 PM". My code :
var TDXRSC = "25/12/2017 4:00 PM";
DateTime.ParseExact(TDXRSC, "dd/MM/yyyy hh:mm tt", CultureInfo.InvariantCulture);
But it's not working.
The issue is your date format expected is dd/MM/yyyy hh:mm tt but the reference date only has a single digit hour 4. You are probably better off not expect leading zeros for days, months or hours.
Try..
var TDXRSC = "25/12/2017 4:00 PM";
var input = DateTime.ParseExact(TDXRSC, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);
This will also still parse 2 digit hours. So var TDXRSC = "25/12/2017 12:00 PM"; will still parse correctly.
var TDXRSC = "25/12/2017 4:00 PM";
var input = DateTime.ParseExact(TDXRSC, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);
var output = input.ToString("MM/dd/yyyy h:mm tt");
When you call ParseExact you're telling the compiler what format the incoming date is. You can then use ToString() method to provide a format for a string representation of the parsed date.
Hope that .TryParseExtract will be more safe to use for conversion, use like the following:
var dateString = "25/12/2017 4:00 PM";
DateTime inputDate;
if(DateTime.TryParseExact(dateString, "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out inputDate))
{
var output = inputDate.ToString("MM/dd/yyyy hh:mm tt");
Console.WriteLine(output);
}
else
{
Console.WriteLine("Conversion failed");
}
Working Example
var TDXRSC = "25/12/2017 4:00 PM";
DateTime date = Convert.ToDateTime(TDXRSC);
string Format = date.ToString("MM/dd/yyyy h:mm tt");

Parsing DateTime to Universal Time C#

I have a xml which can return a time in the format (7/23/2013 4:00pm) my question is: How can I explain to DateTime.ParseExact that I'm in the "am" or in the "pm"? I have this piece of code, but it returns me an exception (String can not be parsed)
I alredy placed an example string (7/23/2013 4:00pm) in which I replace "pm" by the empty chain "".
string pattern = "MM/dd/yyyy H:mm 'UTC' zzz";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
Thank you very much :)
You can pass an array to cover various formats. I use the following for various time inputs.
var formats = new[]
{
"M/dd/yyyy hh:mm tt",
"M/dd/yyyy hh:mmtt",
"M/dd/yyyy h:mm tt",
"M/dd/yyyy h:mmtt",
"M/dd/yyyy hhtt",
"M/dd/yyyy htt",
"M/dd/yyyy h tt",
"M/dd/yyyy hh tt"
};
var date = "7/23/2013 4:00pm";
DateTime time = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
H in your pattern expects the time in a 24 style. You need tt (as outlined in the previous answer) AND you must a small h in your pattern:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";
You need the tt format:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);

String was not recognized as a valid DateTime

DateTime dtEndTime = DateTime.ParseExact(
appToDate,
timeFormats,
null,
System.Globalization.DateTimeStyles.None);
appToDate = 21-02-2013 12:30 AM
string[] timeFormats = {
"dd-MM-yyyy H:m tt",
"dd-MM-yyyy H:mm tt",
"dd-MM-yyyy HH:m tt",
"dd-MM-yyyy HH:mm tt"
};
String was not recognized as a valid DateTime.
I suspect the problem is your use of H combined with tt. H and HH indicate an hour in the range 0-23, where 12 is noon, and therefore PM.
I suspect you want h and hh instead of H... although you shouldn't need every combination of h/H/m/mm. (Do you really expect to see "1:5 PM"?) I suspect just "dd-MM-yyyy H:mm tt" should cover you.

How to check whether a string date can be converted to a DateTime or not?

There is a SQL Server 2008 database for which I have to create a management software. The database contains a column named DateOfCreation. The table designer made this column as string and gave freedom to users to add date in any format they want and this was really a silly mistake by him. Now some users added as "24 Jan" or
"Jan 24" or "1991 1 12" and many unknown formats. What I want is that when I fetch this string date, a function should be called that will check the format and return -1 if date is not in correct format else return the converted date in DD/MM/YYYY. So how can I check the format of the date that string date variable is containing?
use DateTime.TryParseExact with your date format, it will return false in case if the date format is different or invalid.
For multiple formats you can specify multiple formats in a string array and then use that in DateTime.TryParseExact something like:
From MSDN - DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime%)
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
DateTime.TryParse could help to some extent. However, you would be dependent on your user using an appropriate date/time format.
public Tuple<bool, DateTime> GetDateTime(string x)
{
DateTime DT = null;
return Tuple.Create((DateTime.TryParse(x, out DT)), DT)
}
may work. I can't guarantee it though.

Parsing dates and times from string in many combinations

I need to parse dates and times from strings. The Problem is that the strings can have any possible format. But I also get the format strings.
So i get:
Date = "9/15/2010"
Time = "16:12:45"
DateFormat = "M/dd/yyyy"
TimeFormat = "h:mm:ss"
TimeZone = "+2:00:00" // +/- and time in TimeFormat
But i have some problems parsing these strings.
I can't parse the time
DateTime.ParseExact("16:12:45","h:mm:ss",null,DateTimeStyles.None);
does not work and causes a FormatException. What is wrong with this call?
If the DateFormat contains slashes, i need to escape them #"M\/dd\/yyyy". Are there any other chars that would need escaping?
Can i parse the whole DateTime in one? Somehting like:
DateTime.ParseExact(Date+' '+Time+' '+TimeZone,DateFormat+' '+TimeFormat+' +'+TimeFormat,null,DateTimeStyles.None);
What is wrong with this call?
The "h:mm:ss" format string expects the hours element to be in 12-hour format (h); The hours in your string are in 24-hour format so you need to use H instead:
DateTime.ParseExact("16:12:45", "H:mm:ss", null, DateTimeStyles.None);
Are there any other chars that would need escaping?
Any literal character in your string that clashes with a format specifier will need to be escaped. For example, / is the date separator but \/ means the literal / character; : is the time separator but \: means the literal : character; y is one of the year specifiers but \y is the literal y character.
Can i parse the whole DateTime in one?
Yes.
How about this?
var #return = (DateTime?)null;
if (source != null)
{
source = source.Trim();
if (source.Length > 0)
{
var fs = new string[]
{
"d MMMM yyyy h:mm tt",
"d MMMM yyyy h:mm:ss tt",
"d MMMM yyyy HH:mm",
"d MMMM yyyy HH:mm:ss",
"d MMMM yyyy",
"d/M/yy h:mm tt",
"d/M/yy h:mm:ss tt",
"d/M/yy HH:mm",
"d/M/yy HH:mm:ss",
"d/M/yy",
"d/M/yyyy HH:mm",
"d/M/yyyy HH:mm:ss",
"d/M/yyyy h:mm:ss tt",
"d/M/yyyy",
"d/M/yyyy h:mm tt",
"d-MMMM-yy HH:mm",
"d-MMMM-yyyy h:mm tt",
"d-MMMM-yyyy h:mm:ss tt",
"d-MMMM-yyyy HH:mm",
"d-MMMM-yyyy HH:mm:ss",
"d-MMMM-yyyy",
"d-MMM-yy",
"d-MMM-yy h:mm tt",
"d-MMM-yy h:mm:ss tt",
"d-MMM-yy HH:mm",
"d-MMM-yy HH:mm:ss",
"d-MMM-yyyy",
"d-M-yy h:mm tt",
"d-M-yy h:mm:ss tt",
"d-M-yy HH:mm",
"d-M-yy HH:mm:ss",
"d-M-yy",
"d-M-yyyy",
"yyyy/M/d h:mm tt",
"yyyy/M/d h:mm:ss tt",
"yyyy/M/d HH:mm",
"yyyy/M/d HH:mm:ss",
"yyyy/M/d",
"yyyy-M-d h:mm tt",
"yyyy-M-d h:mm:ss tt",
"yyyy-M-d HH:mm",
"yyyy-M-d HH:mm:ss",
"yyyy-M-d",
"yyyy-MM-ddTHH:mm:ss",
};
#return = DateTime.ParseExact(source, fs,
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.None);
}
}
return #return;
Do you know which culture the original string belongs to? If you do you can specify a culture specific DateTimeStyle when calling Parse()
DateTime date = DateTime.Parse("<your specific date>", System.Globalization.CultureInfo.GetCultureInfo("<your culture>").DateTimeFormat);
Create a custom DateTimeFormatInfo and pass that into DateTime.Parse. Like this:
string dateValue = string.Format("{0} {1}", "9/15/2010", "16:12:45");
var customDateTimeFormatInfo = new DateTimeFormatInfo();
customDateTimeFormatInfo.FullDateTimePattern = string.Format("{0} {1}", "M/dd/yyyy", "h:mm:ss");
DateTime dt = DateTime.Parse(dateValue, customDateTimeFormatInfo);
No escaping required and handled your "h:mm:ss" fine with no modification required.

Categories

Resources