axuno / SmartFormat

A lightweight text templating library written in C# which can be a drop-in replacement for string.Format
Other
1.1k stars 105 forks source link

Force delimiter to format DateTime (\/) #120

Closed STARSCrazy closed 5 years ago

STARSCrazy commented 5 years ago

Hello everybody

I have a problem with formatting date values when the delimiter is forced to use "/" or rather "\/". With string.Format this is possible: string.Format( "{0:yyyy\\/MM\\/dd HH:mm:ss}", DateTime.Now ) //Result: 2019/05/09 10:58:47

Important: My CurrentUICulture and CurrentCulture are set to "de-DE". The default date delimiter in German is ".".

My SmartFormat.NET version: 2.4.2

Here are two examples: This works

{
    var now = DateTime.Now;
    var smartFmt = "It is now {Date:yyyy/MM/dd HH:mm:ss}";
    var stringFmt = $"It is now {now.Date:yyyy/MM/dd HH:mm:ss}";
    Assert.AreEqual( stringFmt, Smart.Format( smartFmt, now ) ); //This works!!!
    Assert.IsTrue( stringFmt.Contains( "." ) ); //Contains "." instead of "/". "." is usual in the German date format.
}

This does not work

{               
    var now = DateTime.Now;
    var smartFmt = "It is now {Date:yyyy\\/MM\\/dd HH:mm:ss}"; //"\\/" is the difference
    var stringFmt = $"It is now {now.Date:yyyy\\/MM\\/dd HH:mm:ss}";
    Assert.AreEqual( stringFmt, Smart.Format( smartFmt, now ) ); //Error: It is now Unrecognized escape sequence in literal: "\/"
    Assert.IsTrue( stringFmt.Contains( "/" ) ); //Forced to contain "/" instead of ".". "." is usual in the German date format.
}
axunonb commented 5 years ago

In order to enforce certain date or time separators, the slash is not a character which must be escaped. It is a literal to surround with ' marks like so:

var smartResult = Smart.Format("It is now {Date:yyyy'/'MM'/'dd HH:mm:ss}", DateTime.Now));
var stringFmtResult = $"It is now {DateTime.Now.Date:yyyy'/'MM'/'dd HH:mm:ss}";

This is the same for string.Format and Smart.Format alike.

STARSCrazy commented 5 years ago

Thank you very much, this will help me 👍