Search code examples
c#.netstringstring-interpolation

How to avoid duplicating string format with string interpolation


Is it possible to not repeat the string format yyyy-MM-dd HH:mm:ss in:

Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} {DateTime.Now.AddDays(1):yyyy-MM-dd HH:mm:ss}");

Other than with workarounds like:

Func<string, object, string> _ = string.Format;
var f = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine($"{_(f, DateTime.Now)} {_(f, DateTime.Now.AddDays(1))}")

Solution

  • If you have many fragments to be formatted, I suggest implementing custom culture for this:

    using System.Globalization;
    
    ...
    
    public sealed class MyFormat : IDisposable {
      private CultureInfo m_Saved;
      private CultureInfo m_Current;
    
      public MyFormat() {
        m_Saved = CultureInfo.CurrentCulture;
    
        m_Current = new CultureInfo(m_Saved.Name, true);
    
        m_Current.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
        m_Current.DateTimeFormat.LongTimePattern = "HH:mm:ss";
    
        //TODO: Add more formats' specifications here  
    
        CultureInfo.CurrentCulture = m_Current;
      }
    
      public void Dispose() {
        if (m_Current == CultureInfo.CurrentCulture) 
          CultureInfo.CurrentCulture = m_Saved;
      }
    }
    

    then you can put it as

    using (new MyFormat()) {
      Console.WriteLine($"{DateTime.Now} {DateTime.Now.AddDays(1)}");
    }