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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.