I have below code
inputdatetime value is "2014/09/11 8:06 AM"
dateformat is "yyyy/MM/dd h:mm a"
CultureInfo culture = CultureInfo.InvariantCulture;
string dateforamat = string.Concat(date, " ", time);
returnValue = DateTime.ParseExact(inputDateTime, dateforamat, culture);
I am getting format exception
Use tt instead of a
DateTime.ParseExact("2014/09/11 8:06 AM", "yyyy/MM/dd h:mm tt", CultureInfo.InvariantCulture);
Read: The "tt" Custom Format Specifier
Related
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");
I want to check whether a string contains dates such as 1/01/2000 and 10/01/2000 in dd/MM/yyyy format.
So far I have tried this.
DateTime dDate = DateTime.Parse(inputString);
string.Format("{0:d/MM/yyyy}", dDate);
But how can I check if that format is correct to throw an exception?
string inputString = "2000-02-02";
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
String.Format("{0:d/MM/yyyy}", dDate);
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
you can use DateTime.ParseExact with the format string
DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);
Above will throw an exception if the given string not in given format.
use DateTime.TryParseExact if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.
check Custom Date and Time Format Strings
I think one of the solutions is to use DateTime.ParseExact or DateTime.TryParseExact
DateTime.ParseExact(dateString, format, provider);
source: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx
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);
}
You can use below IsValidDate():
public static bool IsValidDate(string value, string[] dateFormats)
{
DateTime tempDate;
bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
if (validDate)
return true;
else
return false;
}
And you can pass in the value and date formats. For example:
var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
if (IsValidDate(data, dateFormats))
{
//Do something
}
else
{
//Do something else
}
you could always try:
Regex r = new Regex(#"\d{2}/\d{2}/\d{4}");
r.isMatch(inputString);
this will check that the string is in the format "02/02/2002"
you may need a bit more if you want to ensure that it is a valid date like dd/mm/yyyy
Use an array of valid dates format, check docs:
string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);
if(isValidFormat)
{
string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
// maybe throw an Exception
}
Try this
DateTime dDate;
dDate = DateTime.TryParse(inputString);
String.Format("{0:d/MM/yyyy}", dDate);
see this link for more info. http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
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;
}
I have the following code:
IFormatProvider culture = new System.Globalization.CultureInfo("es-ES", true);
date = DateTime.ParseExact(_date, "yyyy-MM-dd hh:mm", culture);
for _date = "2012-11-17 15:00"
it throws an exception
but for _date = "2012-11-17 10:00" works
Anyone can tell me what I'm doing wrong?
use HH instead of hh
date = DateTime.ParseExact(_date, "yyyy-MM-dd HH:mm", culture);
HH is for 24-hr
hh is for 12-hr
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.