Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRY string formatting

What is an elegant way to pull out common formats (e.g. datetime) for string.format into accessible constants?

Ideally I would like to do something like the following, but I get the below error when I try to use this code.

var now = DateTime.Now;
var format = "yyyy-MM-dd";
Console.WriteLine(string.Format("The date is {1:{0}}", format, now));

[System.FormatException: Input string was not in a correct format.] at Program.Main(): line 9

The reasoning behind this is that certain API's require a specific datetime format. I would like to be able to reference a single place to get that format, such that all or none of the calls will work.

I realize that the following will work, but it doesn't seem very elegant.

Console.WriteLine(string.Format("The date is {1:" + format + "}", format, now));
like image 813
Ryan Gates Avatar asked Mar 31 '14 19:03

Ryan Gates


2 Answers

You could go an app constant route - a static class that holds your format strings.

namespace App.Framework {
    public static class AppConstant {
        public static readonly string DisplayDateShort = "MM/dd/yyyy";
    }
}

As far as your example goes, it's kind of flawed; you want to call ToString() on your DateTime value.

Console.WriteLine(now.ToString(AppConstant.DisplayDateShort));

like image 200
48klocs Avatar answered Sep 29 '22 22:09

48klocs


You can find all the used format strings under DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns().

Afterwards you can individually try to parse your input data with each value and see which on returns true (see: DateTime.TryParseExact()).

Console.WriteLine (DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns());

enter image description here

Sample code:

void Main()
{
    var now = DateTime.Now.ToString();

    foreach(var format in DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns()){
        DateTime result;
        if(DateTime.TryParseExact(now, format, CultureInfo.CurrentCulture, DateTimeStyles.None, out result)){
            Console.WriteLine(string.Format("The date is {0}, the format is: {1}", result, format));
        }
    }
}

enter image description here

like image 24
Jeroen Vannevel Avatar answered Sep 29 '22 21:09

Jeroen Vannevel