3

I receive some file from external system, the date/time is represented as 28/Jul/2015:01:02:36 -0500.

What is the best way to parse it in to DateTime type in C#?

5
  • 1
    That looks like a pretty weird format to me. My guess would be you're going to need to use some combination of Regex methods and the DateTime.Parse method. Commented Aug 5, 2015 at 15:50
  • @DanForbes yup, it is from WebSEAL log file. Commented Aug 5, 2015 at 15:51
  • Could you confirm that there is no space and a colon between the year and the hour and there is a space between seconds and -0500? Commented Aug 5, 2015 at 15:51
  • @Steve I confirm. What you see is what I copied from log file as is. Commented Aug 5, 2015 at 15:52
  • 1
    You may want to consider using DateTimeOffset instead of DateTime. Especially if -05:00 is not an offset in your time zone. Commented Aug 5, 2015 at 16:01

3 Answers 3

5

You should look here for more information on Custom Date Formats in C#:

Custom Date Formats on MSDN

However here is some code to get you started.

First, determine the correct format string you expect. and then use ParseExact

static void Main(string[] args)
{
    var date = "28/Jul/2015:01:02:36 -0500";
    var formatstring = "dd/MMM/yyyy:HH:mm:ss K";

    var d = DateTime.ParseExact(date, formatstring, null);
    Console.WriteLine(d);
    Console.ReadLine();
}

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

2

How about this?

DateTime d;
DateTime.TryParseExact(target,"dd/MMM/yyyy:hh:mm:ss zzzz", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out d);

Comments

2

try

CultureInfo provider = CultureInfo.InvariantCulture;
var dateString = "28/Jul/2015:01:02:36 -0500";
var format = "dd/MMM/yyyy:hh:mm:ss zzzz";
var date = DateTime.ParseExact(dateString,format,provider);

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.