0

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?

4
  • 3
    You just want the time part? What have you tried so far? Commented Jan 5, 2012 at 15:14
  • 2
    please show some code... what have you tried ? what didn't work ? Commented Jan 5, 2012 at 15:14
  • Look into DateTime.ParseExact and TryParseExact. Many questions exist here that concern those two methods. Commented Jan 5, 2012 at 15:15
  • i need it in this format "19:58:58 05/Jan/12" Commented Jan 5, 2012 at 15:17

3 Answers 3

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

oh, did not see that parameter. Fixed the code, its just CultureInfo.InvariantCulture
0
var reformatted = input.Substring(4, 17) + input.Substring(22);
return DateTime.Parse(reformatted);

That should work fine.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.