Barry The Wizard
Barry The Wizard

Reputation: 1318

Find dates and change format in C#

I have a text file with different data. Now I need to replace multiple things in the file, before I can use the data correctly. I have replaced texts with Regex. But now I need to change dates. But I can't figure out how to do that.

The dates look like this: "utc": "2017-10-02 19:55:00.205263000 Z" And I want to get this result for all the occurences of this date format: "utc": "2017-10-02 19:55:00"

I tried to use following code:

string pattern = @"{0:yyyy-mm-dd hh:mm:ss.fff Z}";
string replacement = "{0:yyyy-mm-dd hh:mm:ss";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(theInputTextFile, replacement);

Is it not possible to use date formats with regular expressions. Or did I make a mistake in my code?

I used the information from here, for the date formats

Upvotes: 1

Views: 3671

Answers (2)

Abdullah Nehir
Abdullah Nehir

Reputation: 1047

Actually you can give Regex.Replace method a delegate so that you can convert its format. Examine the example in this page: https://msdn.microsoft.com/en-us/library/cft8645c(v=vs.110).aspx

A code sample is below, which finds dates that are formatted as you wrote in the question and replaces with the new format:

class Program
{
    static void Main()
    {
        string text = " dasd arew 2017-03-11 12:25:56.345 Z 2017-03-11 12:25:56.345 Z das tfgwe 2017-03-11 12:25:56.345 Z";
        string pattern = @"\d{4}\-\d{2}\-\d{2}\s\d{2}\:\d{2}\:\d{2}\.\d{3}\sZ";
        Regex r = new Regex(pattern);
        var res = r.Replace(text, new MatchEvaluator(ConvertDateFormat));
        Console.WriteLine(res);
    }

    static string ConvertDateFormat(Match m)
    {
        var mydate = DateTime.Parse(m.Value);
        return mydate.ToString("yyyy-MM-dd hh:mm:ss");
    }

}

Upvotes: 5

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241949

Is it not possible to use date formats with regular expressions

Correct. It is not possible. Regular expressions and date format/parsing tokens are two unrelated concepts. You would need to match for specific text. The internals of a date parser might use a regular expression to achieve such a goal, but one can't simply pass yyyy to a Regex class and expect it to find 2017. You would have to use something like \d{4} for that, and it will catch any four consecutive numbers.

Also note that date format tokens are case sensitive, and you've mixed up minutes (mm) with months (MM) and use 12-hour hours (hh) instead of 24-hour hours (HH) without an am/pm indicator (tt) - not that it would matter here anyway since you pass into a regex.

Upvotes: 0

Related Questions