2

I have a C# application I wrote but my Convert.ToDateTime doesn't work past 09:59 ?

Here is my code:

strDateTime = Convert.ToDateTime(arr[3].TrimStart('[').Substring(0, 11) + " " + arr[3].TrimStart('[').Substring(13, 7));

This is what's in arr[3]:

[20/Feb/2014:14:21:32 +0100]

Its driving me crazy!

Thanks

4
  • 1
    I don't think the first colon should be there
    – Rob
    Feb 25, 2014 at 9:54
  • I think you are catching the : at the end of the date and the time. Please check and see if making the substrings less in length (to exclude the :) would get your required behavior Feb 25, 2014 at 9:55
  • What exactly are you trying to accomplish? Feb 25, 2014 at 9:57
  • Convert.ToDateTime(x.TrimStart('[').Substring(0, 11) + " " + x.TrimStart('[').Substring(12, 8)) - this is the correct version; And please rewrite this with DateTime.ParseExact(); Feb 25, 2014 at 9:58

4 Answers 4

7
string s = "[20/Feb/2014:14:21:32 +0100]";

DateTime d = DateTime.ParseExact(s, @"[dd\/MMM\/yyyy\:HH\:mm\:ss zzzz]", null);
0
2

Your Substring is incorrect. This should work (and is more readable):

string both = arr[3].Trim('[', ']');
string datePart = both.Substring(0, 11);
string timePart = both.Substring(12);
string dateTimePart = string.Format("{0} {1}", datePart, timePart);
DateTime dateTime = DateTime.Parse(dateTimePart);

Or use DateTimeOffSet.Parse:

DateTimeOffset offset = DateTimeOffset.Parse(dateTimePart);
1

with your substring

arr[3].TrimStart('[').Substring(13, 7));

you don't get the whole time out of the string [20/Feb/2014:14:21:32 +0100]

you only get 4:21:32 instead of 14:21:32

try

arr[3].TrimStart('[').Substring(12, 8));
1

Problem 1: You are truncating from 13th index for time but in your string Time starts from 12th character

Solution 1: You should extract the Time from Index position 12 to 20(12+8)th charactercharacter.

Replace This:

arr[3].TrimStart('[').Substring(0, 11) + " " + arr[3].TrimStart('[').Substring(13, 7)

With This:

arr[3].TrimStart('[').Substring(0, 11) + " " + arr[3].TrimStart('[').Substring(12, 8)

Suggestion You need to use DateTime.ParseExact() to parse the datetime in required custom format as below:

 DateTime.ParseExact(str, "dd/MMM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Complete Code:

string arr = "[20/Feb/2014:14:21:32 +0100]";
string str=arr.TrimStart('[').Substring(0, 11) + " " + arr.TrimStart('[').Substring(12, 8);
DateTime strDateTime = DateTime.ParseExact(str, "dd/MMM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.