16

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..

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
Grant
  • 11,138
  • 32
  • 94
  • 140

2 Answers2

28

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx has the relevant parsing, if you're providing your own formatString – Tanzelax Feb 10 '10 at 07:27
7

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

Giorgi
  • 30,270
  • 13
  • 89
  • 125
  • this is the most efficient way to parse a `string` to `DateTime`. parsing with `.Parse()` and `.TryParse()` without format info is f..king damn slow! –  Feb 10 '10 at 07:22