DateTime.TryParse not working as expected - c#

I am trying to get this date string 09 Apr 2015: 15:16:17 to display in this format 09/04/2015 15:16:17. This is what I have tried.
DateTime dtDateTime = new DateTime();
string dateString = "09 Apr 2015: 15:16:17";
DateTime dateValue;
DateTime.TryParse(dateString, out dateValue);
dtDateTime = dateValue;
This is the output 01/01/0001 00:00:00
I thought the TryParse would convert the dateString value to the required DateTime format. What am I doing wrong?

You should go with this:
DateTime dtDateTime = new DateTime();
string dateString = "09 Apr 2015: 15:16:17";
DateTime dateValue;
if (DateTime.TryParseExact(dateString, #"dd MMM yyyy':' HH':'mm':'ss",
new CultureInfo("en-us"), DateTimeStyles.None, out dateValue))
dtDateTime = dateValue;
Using TryParseExact you can provide a custom date format string to match your input date. In the example above I added that extra : after the year.
Also, you must use a CultureInfo which can understand your month name; here I assumed you got an english formatted date.

You need to specify the format since it's not a standard date format string:
DateTime.TryParseExact(
dateString,
"dd MMM yyyy: HH:mm:ss",
CultureInfo.CurrentCulture,
DateTimeStyles.None,
out dateValue);
Also, you should check the result of the call since TryParse and TryParseExact return true/false

You can use TryParseExact method:
DateTime.TryParseExact(dateString, "dd MMM yyyy: HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AllowWhiteSpaces,
out dtDateTime);
Tips:
If you use MMM, the month will be treated as if it is in 3 letter format (like Apr )
If you use HH rather than hh it means the hour part is in 24-hour format, the it will not fail on parsing 15 as hour

Related

convert month name to month number when date is not given

From my UI Iam getting string like 'March 2017' and I want first date of this month in c#.net.how can I achieve this?In jquery calendar only months are visible.so only Iam getting 'March 2017'
I have tried this-
string pattern = "MM-dd-yy";
DateTime parsedDate;
DateTime.TryParseExact(txtDate.Text.Trim(), pattern, null, DateTimeStyles.None, out parsedDate);
You should use proper format string. MMMM represents long month name (just like "March" or "April"). yyyy represents full (4-digit) year. Returned date will be first day of the given month, just like you need:
DateTime parsedDate = DateTime.ParseExact(txtDate.Text.Trim(), "MMMM yyyy", CultureInfo.InvariantCulture);
// or CultureInfo.CurrentCulture, depending on requirements.
Or with TryParseExact:
DateTime parsedDate;
if (DateTime.TryParseExact(txtDate.Text.Trim(), "MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate)) {
// do stuff
}
If month names are always in english (like "March") - use CultureInfo.InvariantCulture. Otherwise - use appropriate culture.

Parse RSS pubdate to DateTime

I get this date string from an RSS:
Wed, 16 Dec 2015 17:57:15 +0100
I need to parse into a DateTime. Ive googled and searched stack overflow and gotten to the following answer (ive tried with only one, two and four 'z' instead of three)
string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
DateTime date = DateTime.ParseExact(dateString, parseFormat,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None);
But I get this error:
System.FormatException: String was not recognized as a valid
DateTime.
Change your code to
string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
DateTime date = DateTime.ParseExact(dateString, parseFormat,
CultureInfo.InvariantCulture);
Hope it helps!
As commented, your format and string matches unless if your CurrentCulture is english-based one. If it is not, it can't parse these Wed and Dec parts successfully.
On the other hand, zzz format specifier does not recommended for DateTime parsing.
From documentation;
With DateTime values, the "zzz" custom format specifier represents the
signed offset of the local operating system's time zone from UTC,
measured in hours and minutes. It does not reflect the value of an
instance's DateTime.Kind property. For this reason, the "zzz" format
specifier is not recommended for use with DateTime values.
However, I would parse it to DateTimeOffset instead of DateTime since you have an UTC Offset in your string like;
var dateString = "Wed, 16 Dec 2015 17:57:15 +0100";
string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
DateTimeOffset dto = DateTimeOffset.ParseExact(dateString, parseFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Now, you have a DateTimeOffset as {16.12.2015 17:57:15 +01:00} which as +01:00 Offset part.

DateTime.TryParseExact returning false for localized date

I am trying to parse a Dutch date from some logfiles but C# DateTime.TryParseExact is always returning false:
DateTime.TryParseExact("mei 21, 2015 12:25:35:719 AM", "MMM dd, yyyy hh:mm:ss:fff tt", new CultureInfo("nl-BE"), DateTimeStyles.None, out date)
Returns false; however I don't see what could be wrong with my date format?
However this returns true:
DateTime.TryParseExact("May 21, 2015 12:25:35:719 AM", "MMM dd, yyyy hh:mm:ss:fff tt", new CultureInfo("en-US"), DateTimeStyles.None, out date) true bool
So that would mean "nl-BE" does not know the word "mei", while en-US has no problem with "May". What can I do to overcome this?
It looks like that culture doesn't use an AM designator:
var culture = new CultureInfo("nl-BE");
Console.WriteLine("x{0}x", culture.DateTimeFormat.AMDesignator);
That prints xx, suggesting that the AM designator is empty.
You can modify this though:
var culture = (CultureInfo) new CultureInfo("nl-BE");
culture.DateTimeFormat.AMDesignator = "AM";
culture.DateTimeFormat.PMDesignator = "PM";
DateTime date;
var result = DateTime.TryParseExact("mei 21, 2015 12:25:35:719 AM",
"MMM dd, yyyy hh:mm:ss:fff tt",
culture,
DateTimeStyles.None, out date);
...
I found the same thing as Jon using a different method. It does round-trip, but no AM/PM designator is used in either direction -- the tt format field neither generates nor matches anything at all.
Test code:
DateTime date;
string fmt = "MMM dd, yyyy hh:mm:ss:fff tt";
Console.WriteLine(DateTime.TryParseExact("May 21, 2015 12:25:35:719 AM", fmt, new CultureInfo("en-US"), DateTimeStyles.None, out date));
CultureInfo dutch = new CultureInfo("nl-BE");
String s = date.ToString(fmt, dutch);
Console.WriteLine(s);
Console.WriteLine(DateTime.TryParseExact(s, fmt, dutch, DateTimeStyles.None, out date));
Output:
True
mei 21, 2015 12:25:35:719
True
In fact, the tt field is solidly broken in that locale, because it does change from a 24-hour to 12-hour clock, but with no differentiation whatsoever between the first and second half of the day.
Online compiler: http://rextester.com/UYR26148

Convert custom date to mysql datetime

I have a custom date format that I want to convert to Datetime so I can then insert into my database, I tried using Datetime.ParseExact() But I think I'm misunderstanding something as the code throws a System.FormatException.
I have the following date format from a csv
> 6/11/2014 9:00
and I wish to convert it to the mysql datetime format
> 0000-00-00 00:00:00 OR yyyy-MM-dd HH:mm:ss
Notice they haven't included the seconds in the original date so I am unsure (without appending them to the end) how to set all records to just have "00" for seconds as it is not available.
I tried the following which throws an exception
DateTime myDate = DateTime.ParseExact("6/11/2014 9:00", "yyyy-MM-dd HH:mm",
System.Globalization.CultureInfo.InvariantCulture);
first thing you need to convert string to date time and than convert datetime tos tring
string strd = "6/11/2014 9:00";
DateTime dt ;
//convert datetime string to datetime
if(DateTime.TryParse(strd, out dt))
{
//convert datetime to custom datetime format
Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}",
dt); ;
}
output
I know this is late to answer that but I'm really surprised none of answer consider to use IFormatProvider to prevent a possible parsing error because of / format specifier or considering your string is a standard date and time format for your CurrentCulture or not so you can or can't use DateTime.TryParse(string, out DateTime) overload directly.
First of all, let's look at what DateTime.ParseExact documentation says:
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they don't match. You should use d/MM/yyyy H:mm format to parse your example string with a culture that have / as a DateSeparator. I almost always suggest to use DateTime.TryParseExact method in this kind of situations;
string s = "6/11/2014 9:00";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy H:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
// result will be 2014-11-06 09:00:00
}
If you know formats of your dates, then you can do this:
string stringDate = "6/11/2014 9:00";
//Your date formats of input
string[] dateFormats = new string[]
{
"d/MM/yyyy H:mm",
"dd/MM/yyyy H:mm",
"dd/MM/yyyy HH:mm",
"dd/MM/yyyy H:mm:ss",
"dd/MM/yyyy HH:mm:ss"
/* And other formats */
};
DateTime convertedDate;
bool isSuccessful = DateTime.TryParseExact(stringDate, dateFormats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out convertedDate);
if (isSuccessful)
{
//If conversion was successful then you can print your date at any format you like
//because you have your date as DateTime object
Console.WriteLine(convertedDate.ToString("dd-MM-yyyy HH:mm:ss")); /* Or other format you want to print */
}
I hope it will be helpful to you.

How to parse a string to DateTime

i have a string date in the following format
Thu Jan 5 19:58:58 2012
I need to parse this string to System.DateTime TimeReceived variable using DateTime.Parse() method.
Any one knows how to parse this string?
You could use the TryParseExact method which allows you to specify a format:
var str = "Thu Jan 5 19:58:58 2012";
DateTime date;
if (DateTime.TryParseExact(str, "ddd MMM d HH:mm:ss yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// the date was successfully parsed, you could use the date variable here
Console.WriteLine("{0:HH:mm:ss dd/MMM/yy}", date);
}
if you look at the ParseExact function, about halfway there's
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
so if you'd switch those around to match what you want, you'll end up with
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date and time with custom specifier.
dateString = "Thu 5 Jan 19:58:58 2012";
format = "ddd MMM dd hh:mm:ss yyyy";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
var reformatted = input.Substring(4, 17) + input.Substring(22);
return DateTime.Parse(reformatted);
That should work fine.

Categories