none
regex date to string RRS feed

  • Question

  • Hello,
    I have the following code:
    string strColHeaderFileDate="20180129";
    string strDateFormat = "^([12]\d{3}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01]))$"; //second if will not go into it...
    string strDateFormat = "yyyyMMdd"; //second if will work...

    How to have a string representation of the regex above?
    For example, as it is now, this code does not go into second if because dtColHeaderFileDate will not be populated
    Note that the datetime.tryparseexact here in my code is expecting strDateFormat to be something like "yyyyMMdd" then the dtColHeaderFileDate  will have a value

    Please note that I would like to use this regex as strDateFormat but in a string format so that the second if gets called. So how this regex above can be converted to string please? thank you

    DateTime dtColHeaderFileDate;
                                                        if (DateTime.TryParseExact(strColHeaderFileDate, strDateFormat, System.Globalization.CultureInfo.InvariantCulture,
                                                        System.Globalization.DateTimeStyles.None, out dtColHeaderFileDate))
                                                        {
                                                            if (dtColHeaderFileDate > DateTime.Today)
                                                            {

    Friday, January 19, 2018 8:18 AM

Answers

  • Hi arkiboys,

    One way is to do is validate first with regx then try to parse with date format. Please look into the below code. See the bold part. Hope this will help you.

    using System;
    using System.Globalization;
    using System.Text.RegularExpressions;
    
    namespace DateForamtString
    {
        class Program
        {
            static void Main(string[] args)
            {
                DateTime dtColHeaderFileDate;
                Regex regex = new Regex(@"^([12]\d{3}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01]))$");
                string strColHeaderFileDate = "20180129";
                Match match = regex.Match(strColHeaderFileDate);
                string strDateFormat = "yyyyMMdd";
                
                if(match.Success)
                {
                    DateTime.TryParseExact(strColHeaderFileDate, strDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dtColHeaderFileDate);
                    if (dtColHeaderFileDate > DateTime.Today)
                    {
                        Console.WriteLine("Hello World!!!");
                    }
                }
                Console.ReadLine();
            }
        }
    }
    


    Thanks,
    Sabah Shariq

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

    Friday, January 19, 2018 9:38 AM
    Moderator