Convert a string to a date in .net - c#

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
}

Related

C# check pattern of a datetime

I have to receive a datetime property through webservice which has two possible formats:
2018-05-14T12:20:45:123+02:00
2018-05-14T12:20:45:123Z
How can I ask to a datetime variable if the pattern is one or another?
yyyy-MM-ddTHH:mm:ss.fffzzz
yyyy-MM-ddTHH:mm:ss.fffZ
You can use TryParseExact which will return bool - true if parse succeed else false:
bool isPattern1 = DateTime.TryParseExact("yourdate string", "yyyy-MM-ddTHH:mm:ss.fffzzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result1);
bool isPattern2 = DateTime.TryParseExact("yourdate string", "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result2);
if(isPattern1)
{
//your code
}
if(isPattern2)
{
//your code
}
OR you can use second overload with string[] as formats parameter if you don't need to actually check which pattern worked, but you need to be sure that string was from this two formats:
var formats = new [] { "yyyy-MM-ddTHH:mm:ss.fffzzz", "yyyy-MM-ddTHH:mm:ss.fffZ" };
bool isParseSucceed = DateTime.TryParseExact("yourdate string", formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result);
DateTime haven't got any format. What you call format is a "format of string representation of DateTime".
You can parse both values with DateTime.Parse() or DateTime.TryParse() - they will work for both.
DateTime.Parse("2018-05-14T12:20:45.123+02:00") // [14.05.2018 15:20:45]
DateTime.Parse("2018-05-14T12:20:45.123Z") // [14.05.2018 15:20:45]
To determine wich format you receive from webservice:
if (responseDateTimeString.EndsWith("Z"))
// it's '2018-05-14T12:20:45.123Z' format
else
// it's not '2018-05-14T12:20:45.123Z' format (it's '2018-05-14T12:20:45.123+02:00')

Why is the DateTime tryparse failing for the date 20140404

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().

String to Date parsing

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);

TryParse special date-format

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.

Convert String to DateTime

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
}

Categories

Resources