如何在 C# 中使用日期格式作为常量?

How to use date format as constant in C#?

我在日期格式化代码中多次使用 "yyyy-MM-dd"

例如:

var targetdate = Date.ToString("yyyy-MM-dd");

是否可以将格式声明为常量,从而避免重复使用代码

用作

const string dateFormat = "yyyy-MM-dd";

//Use 
var targetdate = Date.ToString(dateFormat);

//for public scope
public static readonly string DateFormat = "yyyy-MM-dd";

//Use
var targetdate = Date.ToString(DateFormat);
//from outside the class, you have to use in this way
var targetdate = Date.ToString(ClassName.DateFormat);

像这样一次又一次地使用扩展方法而不声明任何格式:

public static class DateExtension
{
    public static string ToStandardString(this DateTime value)
    {
        return value.ToString(
            "yyyy-MM-dd", 
            System.Globalization.CultureInfo.InvariantCulture);
    }
}

原来你是这样用的

var targetdate = Date.ToStandardString();

您可以做的另一个选择是在 .ToString(...) 上使用 DateTimeFormatInfo 重载而不是 string 重载。

public static readonly System.Globalization.DateTimeFormatInfo MyDateTimeFormatInfo
    = new System.Globalization.DateTimeFormatInfo()
{
    ShortDatePattern = "yyyy-MM-dd",
    LongTimePattern = "",
};

现在您可以执行 var targetdate = DateTime.Now.ToString(MyDateTimeFormatInfo);,这与使用字符串非常相似,但您可以更好地控制许多其他格式设置属性。