DateTime TryParse problem - c#

string date = txtWorkingDate.Text;
DateTime dateTime = DateTime.MinValue;
if (DateTime.TryParse(date, out dateTime))
{
args.IsValid = true;
}
else
args.IsValid = false;
txtWorkingDate.Text is like "dd.MM.yyyy" becouse of this validateion is always false if date is not like "dd.MM.yyyy". How c an i check types of date like "dd.MM.yyyy", "MM/dd/yyyy" becouse are all valid.

By using this overload and providing the accepted formats:
string date = txtWorkingDate.Text;
DateTime dateTime;
string[] formats = new[] { "dd.MM.yyyy", "MM/dd/yyyy" };
if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}

System.Globalization.CultureInfo cultureinfo =
new System.Globalization.CultureInfo("en-gb");
DateTime dt = DateTime.Parse("13/12/2009", cultureinfo);
You need to specify the culture assuming you know it.

You can use the
DateTime.TryParse(
string s,
IFormatProvider provider,
DateTimeStyles styles,
out DateTime result
)
overload.
Also, you don't need the if, you can simply write
args.IsValid = DateTime.TryParse(...);
As DateTime.TryParse() already returns a bool.

Related

DateTime Format check

Quick Question
Value passed in ActivationDate or ExpirationDate string, must be in either of the two formats stated below:Format 1:YYYY-MM-DD & Format 2: YYYY-MM-DD HH:MM
If the date values are not in either of the above format, then it should report back appropriate error message.
Any clue? Thanks in advance
You can use DateTime.TryParseExact, using a string[] with the valid formats:
string[] formats = new string[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm" };
string s = "2017-12-01 12:23";
DateTime date;
bool converted = DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
With this code, you get in convertedif the input date was in a valid format, and in date the parsed DateTime
You can use ParseExact() with try-catch:
string date = "2017-02-01";
DateTime dt = default(DateTime);
try
{
dt = DateTime.ParseExact(date, new string[] {"yyyy-MM-dd", "yyyy-MM-dd hh:mm"}, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
catch (FormatException ex)
{
//error
}
OR
Use TryParseExact():
string date = "2017-02-01";
DateTime dt;
if (DateTime.TryParseExact(date, new string[] {"yyyy-MM-dd", "yyyy-MM-DD hh:mm"}, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//do something and use "dt" variable
}
else
{
//error
}

Fixing Dates in C#

I am trying to create a textbox that will translate 1225 to 12/25/13. After having done a lot of research, I think "DateTime.TryParseExact" is what I need to use, but I can't get it to work. Here is my code:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateValue;
string[] DateTimeFormats = new string[]{
"MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
"M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
"MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
"MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
"MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
"MMddyy HHmm","MMddyy HHmmss",
"MMddyyyy HHmm","MMddyyyy HHmmss",
"yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss"};
if (DateTime.TryParseExact(TheTextBox.Text, DateTimeFormats, provider, DateTimeStyles.None, out dateValue))
{
TheTextBox.Text = dateValue.ToString("d MMMM yyyy");
}
Any ideas how to fix this?
If it is possible to predict all possible formats, then you can try something like this
static void Main(string[] args)
{
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;
dateString = "0501";
var dateFormats = new String[] {"MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
"M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
"MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
"MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
"MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
"MMddyy HHmm","MMddyy HHmmss",
"MMddyyyy HHmm","MMddyyyy HHmmss",
"yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss", "MMdd"};
bool matchFound = false;
foreach (var dateFormat in dateFormats)
{
if (DateTime.TryParseExact(dateString, dateFormat, enUS, DateTimeStyles.None, out dateValue))
{
matchFound = true;
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue.ToString("dd MM yyyy"), dateValue.Kind);
}
}
if (!matchFound)
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
Console.ReadKey();
}
For the example you provided consider the following change to your code...
string[] DateTimeFormats = new string[]{"MMdd"};
You can use DateTime.ParseExact to translate your string into a DateTime:
The text of the textBox1 is 1225:
DateTime date = DateTime.ParseExact(textBox1.Text,"MMdd",CultureInfo.InvariantCulture);
string yourDate = date.ToString("MM/dd/yy"));
//yourDate is 12/25/13
Note: This will always return the date with the current year (here: 2013).

Date format from Dutch to English

I have a date in string format (i.e in Dutch language), like "7 juli 2013". I want to convert it in English format. "Convert.toDateTime(strValue) throw exception as that converts only English format. I also try this
string strValue = "7 juli 2013";
CultureInfo ci = new CultureInfo("en-US");
strValue = strValue.ToString(ci);
but this is not working. What is the way to convert it?
string strValue = "7 juli 2013";
// Convert to DateTime
CultureInfo dutch = new CultureInfo("nl-NL", false);
DateTime dt = DateTime.Parse(strValue, dutch);
// Convert the DateTime to a string
CultureInfo ci = new CultureInfo("en-US", false);
strValue = dt.ToString("d MMM yyyy", ci);
You first convert the string to a DateTime, then .ToString the DateTime!
And, in general, it's false that Convert.ToDateTime uses only English. The overload you used uses the current culture of your pc (so on my pc it uses italian), and there is the Convert.ToDateTime(string, IFormatProvider) overload that accepts a CultureInfo.
Multilanguage... But note that this is wrong! You can't be sure that a word doesn't have different meaning in different places!!!
// The languages you want to recognize
var languages = new[] { "nl-NL", "it-IT" };
DateTime dt = DateTime.MinValue;
bool success = false;
foreach (var lang in languages)
{
if (DateTime.TryParse(strValue, new CultureInfo(lang, false), DateTimeStyles.AssumeLocal, out dt))
{
success = true;
break;
}
}
if (success)
{
CultureInfo ci = new CultureInfo("en-US", false);
strValue = dt.ToString("d MMM yyyy", ci);
}

String was not recognized as a valid DateTime

This is my first post here. The application is a winform I have set the culture for the application as en-GB but while checking and saving I convert it back to en-US I get this the error String was not recornized as a valid DateTime
CultureInfo currentCulture = new CultureInfo("en-US");
string strCheckDate = CheckConvertCulture(input);
string date = DateTime.Now.ToString("M/d/yyyy");
if (DateTime.ParseExact(strCheckDate,currentCulture.ToString(),null)> DateTime.ParseExact(date,currentCulture.ToString(),null))
{
return false;
}
else
{
return true;
}
What am I doing wrong here
This is my converCurrentCulture code
string strdate = string.Empty;
CultureInfo currentCulture = CultureInfo.CurrentCulture;
System.Globalization.DateTimeFormatInfo usDtfi = new System.Globalization.CultureInfo("en-US", false).DateTimeFormat;
if (currentCulture.ToString() != "en-US")
{
strdate = Convert.ToDateTime(Culturedate).ToString(usDtfi.ShortDatePattern);
}
else
{
strdate = Culturedate;
}
return strdate;
This is what I did to get it to work, but if a user selects an invalid date like 29/02/2013 will it work not sure,
CultureInfo currentCulture = new CultureInfo("en-GB");
string date = DateTime.Now.ToString("dd/MM/yyyy", currentCulture);
Since the application is default to en-GB
if (DateTime.Parse(input) > DateTime.Parse(date))
{
return false;
}
else
{
return true;
}
If this is actually your code:
CultureInfo currentCulture = new CultureInfo("en-US");
string strCheckDate = CheckConvertCulture(input);
if (DateTime.ParseExact(strCheckDate,currentCulture.ToString(),null)
then the problem is in your ParseExact, which translates to
if (DateTime.ParseExact(strCheckDate, "en-US", null))
You would be better off specifying the date in a specific format, and parsing that:
string format = "MM/dd/yyyy HH:mm:ss";
string strCheckDate = input.ToString(format);
// See note below about "why are you doing this?
if (DateTime.ParseExact(strCheckDate, format))
My big question is - why are you doing this? If you have two dates, why are you converting them both to strings, and then converting them back to dates to compare them?
return (input > date);
Please see the MSDN documentation for the proper use of DateTime.ParseExact.

Format string as date

I have a string 20100524 (2010 05 24) and I would like to parse it as an actual date format.
This will do it for you in a safe manner:
DateTime dateTime;
if (DateTime.TryParseExact("20100524", "yyyyMMdd", null, DateTimeStyles.None, out dateTime))
{
// use dateTime here
}
else
{
// the string could not be parsed as a DateTime
}
DateTime.Parse and Datetime.ParseExact are your friends.
DateTime.ParseExact("20100524", "yyyyMMdd", Thread.CurrentThread.CurrentCulture);
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "20100524";
string format = "yyyyMMdd";
result = DateTime.ParseExact(dateString, format, provider);

Categories