Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing non-standard date formats with DateTime.TryParseExact

Hi Im trying to parse date strings like "1012012", "1st January 2012".

  1. read the Api It says to use d,%d where the date does not have a leading 0. Cant get it working for dates like "1012012"

  2. trying to use "d MMM YYYY" for "1st January 2012", what do I use so 'st', 'th' works?

    using System;
    using System.IO;
    using System.Globalization;
    
    namespace test
    {
      class Script
      {
        static public void Main(string [] args)
        {
    
            //String dateString = "9022011";  // q1
            String dateString = "9th February 2011";  //q2
            System.DateTime date = DateTime.MinValue;
            string[] format = { "ddMMyyyy", "d MMM yyyy" }; // what would be the correct format strings?
    
            if (DateTime.TryParseExact(dateString,format,new CultureInfo("en-AU"),DateTimeStyles.None,out date))
                            {
                Console.Out.WriteLine(date.ToString());
            } 
                            else
                            {
                Console.Out.WriteLine("cant convert");
            }
         }
      }
    
    }
    
like image 446
P H Avatar asked Aug 29 '11 08:08

P H


People also ask

What formats does DateTime parse?

Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.sssZ ) is explicitly specified to be supported.

What does DateTime ParseExact do?

The DateTime. ParseExact(String, String, IFormatProvider) method parses the string representation of a date, which must be in the format defined by the format parameter.

How can I get only the date from DateTime format?

ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.

How do you check if the date is in dd mm yyyy format in C #?

Use DateTime. TryParseExact to try to parse it: string text = "02/25/2008"; DateTime parsed; bool valid = DateTime. TryParseExact(text, "MM/dd/yyyy", CultureInfo.


1 Answers

var dateString = "1st February 2011";
DateTime date;
var replaced = dateString.Substring(0,4)
                         .Replace("nd","")
                         .Replace("th","")
                         .Replace("rd","")
                         .Replace("st","")
                         + dateString.Substring(4);

DateTime.TryParseExact(replaced, "d MMMM yyyy",
                       new CultureInfo("en-us"), DateTimeStyles.AssumeLocal, 
                       out date);

should do the trick (sorry the 'th' is nasty) - you have to take some care with the st (August) - just remove it only from the first few appearances:

like image 172
Random Dev Avatar answered Sep 29 '22 07:09

Random Dev