I have a string like this:
"20090212"
and I want to convert to valid C# datetime.
Do I need to parse it out because that seems too much work?
You can use DateTime.ParseExact:
DateTime result =
DateTime.ParseExact("20090212", "yyyyMMdd", CultureInfo.InvariantCulture);
Have a look at the DateTime.TryParseExact method (MSDN). I prefer TryParseExact method to the ParseExact method because it returns a boolean telling you whether or not the conversion was successful instead of throwing an exception but either one will work.
DateTime.ParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture);
... and I really doubt I got there first.
Although for completeness, I prefer TryParseExact
DateTime dt;
if(DateTime.TryParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt)) {
// ... use the variable dt
}
Related
I wrote a simple unit test that fails when trying to parse the date "20140404".
DateTime dt;
DateTime.TryParse("20140404", out dt);
Assert.IsTrue(dt.Year == 2014 && dt.Month == 4 && dt.Day == 4);
Can someone clear this up for me, should I be passing in the expected format?
On my webpage form, I said I want users to enter the format yyyymmdd.
You need to supply the format in DateTime.TryParseExact.
DateTime dt;
DateTime.TryParseExact("20140404",
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
You can also validate if the parsing was successful or not
DateTime dt;
if (DateTime.TryParseExact("20140404",
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//parsing successfull
}
else
{
//parsing failed
}
TryParse group of methods returns a boolean value indicating if parsing was successful or not. When the parsing fails it returns false instead of raising an exception and the out variables is assigned the default value. That is why your Test is failing, since dt was assigned the default value dt = {01/01/0001 12:00:00 AM}.
Why parsing with TryParse was failing in your case? , because DateTime.Parse and DateTime.TryParse use already defined date formats in DateTimeFormatInfo Class. Your format is not one of them.
You'd need to specify a custom format string and use TryParseExact:
bool success = DateTime.TryParseExact(
"20140404",
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
// Check success
If you're going to ignore the return value, you'd be better off using ParseExact instead of TryParseExact, as you'd get an exception in that case if you feed bad data.
As to why it doesn't work: DateTime.TryParse iterates over the standard formats inside DateTimeFormatInfo and this isn't among the list.
You can verify this by executing
new DateTimeFormatInfo().GetAllDateTimePatterns().ToList().ForEach(Console.WriteLine);
If you don't want to use ParseExact, you can add your own formats to this collection using SetAllDatePatterns().
I am getting a string and i want to parse that string as date and want to store it in DataTable.
string can be in formats
1- "2014/23/10"
2- "2014-23-10"
{
string st="2014/23/10";
string st="2014-23-10";
}
And attach time with it.
Any idea to make it possible ?
DateTime.ParseExact or DateTime.TryParseExact are appropriate here - both will accept multiple format strings, which is what you need in this case. Make sure you specify the invariant culture so that no culture-specific settings (such as the default calendar) affect the result:
string[] formats = { "yyyy-MM-dd", "yyyy/MM/dd" };
DateTime date;
if (DateTime.TryParseExact(input, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
// Add date to the DataTable
}
else
{
// Handle parse failure. If this really shouldn't happen,
// use DateTime.ParseExact instead
}
If the input is from a user (and is therefore "expected" to be potentially broken, without that indicating an error anywhere in the the system), you should use TryParseExact. If a failure to parse indicates a significant problem which should simply abort the current operation, use ParseExact instead (it throws an exception on failure).
Since both are not standart date and time format, you can use DateTime.ParseExact method like;
string st = "2014/23/10";
string st1 = "2014-23-10";
var date = DateTime.ParseExact(st,
"yyyy/dd/MM", CultureInfo.InvariantCulture);
var date1 = DateTime.ParseExact(st1,
"yyyy-dd-MM", CultureInfo.InvariantCulture);
Output will be;
10/23/2014 12:00:00 AM
10/23/2014 12:00:00 AM
Here a demonstration.
Of course these outputs depends your current culture thread.
If you want to format your DateTime's as a string representation, you can use DateTime.ToString(string) overload which accepts as a string format.
Since you have more than one format, you can use DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload which is takes your formats as a string array.
var formats = new []{"yyyy-MM-dd", "yyyy/MM/dd"};
DateTime dt;
if(DateTime.TryParseExact(st, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//
}
else
{
//
}
Convert to a DateTime with DateTime.TryParseExact(); or even DateTime.Parse if you need to be flexible. Then you can format it back out however you like!
See: http://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
Try
DateTime.Parse(st, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Set DateTimeStyles based on your requirement.
Try this:
DateTime.Parse(st);
If It the above line not works for you, then add cultrureInfo below:
DateTime.ParseExact(st,"yyyy/dd/MM", CultureInfo.InvariantCulture);
I am trying to convert the
string date = "31.03.2013"
to a DateTime. Here is my code:
Convert.ToDateTime(date,CultureInfo.InvariantCulture);
I am getting a Format Exception.
According to http://msdn.microsoft.com/en-us/library/vstudio/cc165448.aspx it should work.
Thanks
The invariant culture is based on en-US, where . is not a the date separator.
You need to use the correct culture, such as fr-FR, which does use . as a date separator.
You could also use DateTime.ParseExact or DateTime.TryParseExact with the exact format string.
Convert.ToDateTime("31.03.2013", CultureInfo.GetCultureInfo("fr-FR"))
Or
DateTime.ParseExact("31.03.2013",
"dd.MM.yyyy",
CultureInfo.InvariantCulture)
Will work.
How about
DateTime.ParseExact(date,"dd.MM.yyyy",null);
You could try to use the DateTime.ParseExact method. It should do the trick for you.
DateTime.ParseExact("31.03.2013", "dd.MM.yyyy", CultureInfo.InvariantCulture);
Use this code --
DateTime.ParseExact(date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
You can try this with DateTime.TryParseExact :
string date = "31.03.2013";
DateTime dateConverted;
DateTime.TryParseExact(date, new string[] { "dd.MM.yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateConverted);
Console.WriteLine(dateConverted);
I try to parse a date-time stamp from an external system as following:
DateTime expiration;
DateTime.TryParse("2011-04-28T14:00:00", out expiration);
Unfortunately it is not recognized. How can I parse this successfully?
sl3dg3
Specify the exact format you want in DateTime.TryParseExact:
DateTime expiration;
string text = "2011-04-28T14:00:00";
bool success = DateTime.TryParseExact(text,
"yyyy-MM-ddTHH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out expiration);
you can use DateTime.TryParseExact instead.
How to create a .NET DateTime from ISO 8601 format
Try this
DateTime expiration;
DateTime.TryParse("2011-04-28 14:00:00", out expiration);
Without using "T".
You need to append "00000Z" to your string argument.
DateTime.TryParse("2011-04-28T14:00:0000000Z", out expiration);
User DateTime.TryParseExact function as following:
DateTime dateValue;
if (DateTime.TryParseExact(dateString, "yyyy-MM-ddTHH:mm:ss",
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
{
// Do Something ..
}
Read about DateTime.
I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
or
DateTime result;
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
More info in the MSDN documentation on ParseExact and TryParseExact.
you could try also TryParseExact for set exact format.
method, here's documentation: http://msdn.microsoft.com/en-us/library/ms131044.aspx
e.g.
DateTime outDt;
bool blnYYYMMDD =
DateTime.TryParseExact(yourString,"yyyyMMdd"
,CultureInfo.CurrentCulture,DateTimeStyles.None
, out outDt);
I hope i help you.
DateTime.TryParse method
You can also do Convert.ToDateTime
not sure the advantages of either
Using TryParse will not throw an exception if it fails. Also, TryParse will return True/False, indicating the success of the conversion.
Regards...
You can use the TryParse method to check validity and parse at same time.
DateTime output;
string input = "09/23/2008";
if (DateTime.TryParseExact(input,"MM/dd/yy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output) || DateTime.TryParseExact(input,"yyyyMMdd", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output))
{
//handle valid date
}
else
{
//handle invalid date
}