How to put unprocessed (escaped) words inside String.Format

前端 未结 4 1334
我寻月下人不归
我寻月下人不归 2020-12-30 21:15

I am formatting a date:

str = String.Format(\"{0:MMM d m:mm\"+yearStr+\"}\", dt);

I want to put the word \"at\" after the \"d\", but I don\

相关标签:
4条回答
  • 2020-12-30 21:22
    string.Format(@"{0:MMM d \a\t m:mm" + yearStr + "}", dt);
    

    Note the double escaping - I used a varbatim string so I was able to write \ inside the string as a normal character. The formatting routine for DateTime then interprets this (again) as an escape sequence.

    Here is a simpler variant:

    string.Format("{0:MMM d} at {0:m:mm" + yearStr + "}", dt);
    

    The first variant might be considered disgusting by some. The latter one is very clear to read, though.

    0 讨论(0)
  • 2020-12-30 21:37

    You can surround literal strings with quotes, which for longer strings is probably easier and a bit more readable than escaping every character with a backslash:

    str = String.Format("{0:MMM d 'at' m:mm"+yearStr+"}", dt);
    

    See Custom Date and Time Format Strings in MSDN Library (search for "Literal string delimiter").

    (And did you mean h:mm instead of m:mm?)

    0 讨论(0)
  • 2020-12-30 21:41

    Using string interpolation (C# 6.0+): (documentation)

    var yearStr = "2018";
    var dt = DateTime.Now;
    var str = $"{dt:MMM d \'at\' H:mm} {yearStr}";
    

    Backslash is optional

    var str = $"{dt:MMM d 'at' H:mm} {yearStr}";
    

    see in action: DotnetFiddle

    0 讨论(0)
  • 2020-12-30 21:42

    Just for fun, but works.

    var what=new object[] { "{{{{0:MMM d}}}} {0} {{{{0:m:mm:{{0}}}}}}", "at", yearStr, dt };
    var that=what.Aggregate((a, b) => String.Format((String)a, b));
    

    You can merge two lines in one. The at which you want to put between two formats is also parameterized.

    0 讨论(0)
提交回复
热议问题