Parsing a date / time string in a specific format

I am getting some file from external system, date / time appears as 28/Jul/2015:01:02:36 -0500

.

What's the best way to parse it DateTime

in C #?

+3


source to share


3 answers


How about this?



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

      

+2


source


You can see more information about custom date formats in C # here:

Custom Date Formats on MSDN

However, here is some code to get you started.



First, define the correct format string that you expect. and then useParseExact

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!

+5


source


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

      

+2


source







All Articles