Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse DateTime in c# from strange format

if i have a datetime string in a weird format, such as YYYY##MM##DD HH**M**SS, how can i create a new datetime object base on that? i have read something about the datetimeformatinfoclass but not sure how to get it working..

like image 711
Grant Avatar asked Feb 10 '10 07:02

Grant


People also ask

What does datetime parse do?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.

What is datetime ParseExact in C #?

The DateTime. ParseExact method converts the specified string representation of a datetime to a DateTime . The datetime string format must match the specified format exactly; otherwise an exception is thrown. Date & time is culture specific; the methods either use the current culture or accept a specific culture.

What is parse c3?

Parse(String, NumberStyles) Converts the string representation of a number in a specified style to its 32-bit signed integer equivalent.


2 Answers

You can use DateTime.ParseExact, or DateTime.TryParseExact for data which you're not confident in. For example:

using System;

class Test
{
    static void Main()
    {
        string formatString = "yyyy'##'MM'##'dd' 'HH'*'mm'*'ss";
        string sampleData = "2010##02##10 07*22*15";
        Console.WriteLine(DateTime.ParseExact(sampleData,
                                              formatString,
                                              null));
    }
}

The quotes in the format string aren't strictly necessary - this will work too:

string formatString = "yyyy##MM##dd HH*mm*ss";

However, using the quotes means you're being explicit that the characters between the quotes are to be used literally, and not understood as pattern characters - so if you changed "#" to "/" the version using quotes would definitely use "/" whereas the version without would use a culture-specific value.

The null in the call to ParseExact means "use the current culture" - in this case it's unlikely to make much difference, but a commonly useful alternative is CultureInfo.InvariantCulture.

It's unfortunate that there's no way of getting the BCL to parse the format string and retain the information; my own Noda Time project rectifies this situation, and I'm hoping it'll make parsing and formatting a lot faster - but it's far from production-ready at the moment.

like image 133
Jon Skeet Avatar answered Sep 18 '22 18:09

Jon Skeet


You can use DateTime.ParseExact method and pass the format you need.

like image 28
Giorgi Avatar answered Sep 17 '22 18:09

Giorgi