I am reading string inputs from an excel sheet and I want to check if the string is a valid date.
To do so, I have:
public static bool IsValidDate(string DateStr)
{
DateStr = DateStr.Trim();
DateTime tempDate = new DateTime().Date;
return DateTime.TryParse(DateStr, out tempDate);
}
The problem in here is that in case that string is 13/12/2021 it will return false(not valid) because set 13 as month and 12 as day.
What is the proper approach to manipulate string format and do a right check inside the same function?
Any help is welcome!
Try this:
public static bool IsValidDate(string DateStr)
{
DateStr = DateStr.Trim();
DateTime tempDate = new DateTime().Date;
return DateTime.TryParse(DateStr, new System.Globalization.CultureInfo("de-DE"), System.Globalization.DateTimeStyles.None, out tempDate);
}
You have to extend the method to take a CultureInfo/DateTimeFormatInfo that uses a format string which starts with the days instead of the month. You could use this:
public static bool IsValidDate(string dateStr, out DateTime theParsedDateTime, IFormatProvider fp = null)
{
if (fp == null)
fp = DateTimeFormatInfo.InvariantInfo;
return DateTime.TryParse(dateStr.Trim(), fp, DateTimeStyles.None, out theParsedDateTime);
}
Now you can call this method in this way, i have used german CultureInfo because that is a working example. Note that InvariantInfo doesn't work because it starts with months:
bool valid = IsValidDate("13/12/2021", out DateTime parsedDate, new CultureInfo("de-DE"));
You have to create a CultureInfo with CultureInfo.CreateSpecificCulture.
And then parse the string using the specific culture.
Just see the example under.
This works for me.
public static bool IsValidDate(string DateStr)
{
return DateTime.ParseExact(DateStr, "dd/MM/yyyy", null);
}
Related
I am trying to convert a datatime string "including milliseconds" into a DataTime. I tried tried to use DateTime.TryParseExact but it does not give me a milliseconds.
Here is what I have tired
public static DateTime? dateTimeVal(string raw, string format = null)
{
DateTime final;
if(raw != null){
if( format != null){
string[] formats = new[] { format };
if (DateTime.TryParseExact(raw, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out final))
{
return final;
}
}
if (DateTime.TryParse(raw, out final))
{
return final;
}
}
return null;
}
This is how I use the method above
DateTime? dt = dateTimeVal("2016-03-14 11:22:21.352", "yyyy-MM-dd HH:mm:ss.fff");
However, dt gives me this 3/14/2016 11:22:21 AM
How can I get the value to include the milliseconds?
DateTime final = new DateTime();
var test = DateTime.TryParseExact("2016-03-14 11:22:21.352", new string[] { "yyyy-MM-dd HH:mm:ss.fff" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
This works for me.
Just take care for your fff. If you write them uppercase, the milliseconds will be supressed. Lowercase they will be parsed.
The only thing away from that I can imagine is you have used .ToString without providing any format. Then you'll get:
Are you sure you've written the providing format lowercase inside your code? Also have you used .ToString() with an output-format that shows up the milliseconds?
If you want to get the DateTime as string with milisecond, then you can use the following code;
string dateTime = dt.Value.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Hope this helps.
I have a method,
public static DateTime ToDate(this object value)
{
return DateTime.ParseExact(value.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture);
}
When i run this code with this code,
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(DateTime.Now.ToDate().ToString());
}
And there is a error on program like this,
String was not recognized as a valid DateTime
How can i solve this problem?
Thanks.
The problem you're having is that your extension method tries to parse the string specifically in the dd.MM.yyyy format. And you're testing your extension method using the DateTime.Now which returns a DateTime in a format of a current culture on your machine (including hours, minutes, etc.), which may may not be in a dd.MM.yyyy format. You can test your extension method as follows: DateTime.Now.ToString("dd.MM.yyyy").ToDate()
However, If I understand correctly what you're trying to do it is better to change the extension method as follows.
public static DateTime ToDate(this string value, string format)
{
return DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
}
and use it as follows
private void button1_Click(object sender, EventArgs e)
{
// Testing the extension method.
MessageBox.Show(DateTime.Now.ToString("dd.MM.yyyy").ToDate("dd.MM.yyyy").ToString());
}
Or, if you specifically receive a DateTime in dd.MM.yyyy because of the localization it is better to set the culture of your application globally like so.
// Substitute appropriate culture.
Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU");
Thread.CurrentThread.CurrentCulture = new CultureInfo("ru-RU");
That way you will not need your extension method since the DateTime will always be in the correct format.
your first function must be as follow :
public static DateTime ToDate(this object value)
{
string date = value.ToString("dd.MM.yyyy");
DateTime dt = Convert.ToDateTime(date);
return dt;
}
I suggest to use the TryParseExact
Then you choose the date format that you need
For example :
public static DateTime ToDate(this object value)
{
DateTime OutputDate ;
DateTime.TryParseExact(value, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out OutputDate);
return OutputDate ?? DateTime.Now ;
}
In the example : the format is "dd.MM.yyyy" and the input date string is value. The OutputDate will take as value the new datetime object and if the instruction fails it will take null.
Please, verify the format of the date and replace it in the example above if you need
I have the following method in order to verify whether a string is a valid datetime:
public bool isDate(string date)
{
bool check = false;
try
{
DateTime converted_date = Convert.ToDateTime(date);
check = true;
}
catch (Exception)
{
check = false;
}
return check;
}
Now, the exception "String was not recognized as valid datetime" is caught whenever I try to pass a string like this:
"12/31/2013 12:00:00 AM"
I cannot understand why this is happening. Can someone help me solve this please?
Instead of the try/catch block, try the built in TryParse method in the DateTime class. It takes your string as a parameter and if it converts successfully it will place the value in the "result" variable. It returns a boolean value representing whether it worked or not.
public bool isDate(string date)
{
var result = new DateTime();
return DateTime.TryParse(date, out result);
}
Most likely your current culture settings are different from the format date is provided in. You can try specifying the culture explicitly:
CultureInfo culture = new CultureInfo("en-US"); // or whatever culture you want
Convert.ToDateTime(date, culture);
You can also use DateTime.TryParseExact and pass a format string (eg. MM/dd/yy H:mm:ss zzz, see more here) to check if the date has a specific format.
I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Please help.
You are looking for the DateTime.Parse() method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
You need an uppercase M for the month part.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Lowercase m is for outputting (and parsing) a minute (such as h:mm).
e.g. a full date time string might look like this:
string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");
Notice the uppercase/lowercase mM difference.
Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.
public static class DateTimeMyFormatExtensions
{
public static string ToMyFormatString(this DateTime dt)
{
return dt.ToString("MM/dd/yyyy");
}
}
public static class StringMyDateTimeFormatExtension
{
public static DateTime ParseMyFormatDateTime(this string s)
{
var culture = System.Globalization.CultureInfo.CurrentCulture;
return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
}
}
EXAMPLE: Translating between DateTime/string
DateTime now = DateTime.Now;
string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();
Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.
System.Globalization.CultureInfo.CurrentCulture.
The only easy way you can do is to roll a custom extension method.
Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.
Solution
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
I did like this
var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
You can change the format too by doing this
string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
// this change the "/" for the "-"
The following works for me.
string strToday = DateTime.Today.ToString("MM/dd/yyyy");
What's the best way to do it?
This is how I'll usually do it:
DateTime newDate;
try
{
newDate = DateTime.Parse(Textbox.Text);
}
catch
{
//isn't a datetime
return;
}
//do stuff with the date
But something tells me that that is a bit wrong. Any ideas?
Use the DateTime.TryParse method instead of using your own try/catch blocks.
string text = "10/16/2009";
DateTime result;
if (DateTime.TryParse(text, out result))
{
// success, result holds converted value
}
else
{
// failed
}
The best pattern to use for datetime parsing would be this
string DateFormat = "dd/MM/yyyy"; //Or any other format
DateTime dateTime;
bool success = DateTime.TryParseExact(value, DateFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime);
Never use DateTime.Parse and even DateTime.TryParse
If you know what the format of the datetime will be, you can also use DateTime..::.TryParseExact Method
The DateTime.TryParse can cause problems when it is used with dates such as 01/03/2009
Is it 01 Mar or 03 Jan?
I would rather recomend that you use something other than a textbox, like a date picker, or validate the textbox so that you have something like dd MMM yyyy. very seldomly would you go wrong with that.
Little addition to previous answers:
DateTime:
public static DateTime Parse(string s)
{
return DateTimeParse.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None);
}
public static bool TryParse(string s, out DateTime result)
{
return DateTimeParse.TryParse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result);
}
DateTimeParse:
internal static DateTime Parse(string s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
{
DateTimeResult result = new DateTimeResult();
result.Init();
if (!TryParse(s, dtfi, styles, ref result))
{
throw GetDateTimeParseException(ref result);
}
return result.parsedDate;
}
TryParse is better
References:
Reflector
Try the following:
DateTime todate;
if(!DateTime.TryParse("2009/31/01", todate))
{
//------------conversion failed-------------//
}