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

9

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

例如:

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

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


1
为什么不改变文化,使其自动应用于整个系统? - Mahesh Malpani
3个回答

10

使用扩展方法时不需要一遍又一遍地声明任何格式,就像这样:

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();

2
你应该提到这个方法必须在静态类中是静态的。 - Scoregraphic
4
我建议在这里也使用不变文化 - 我非常怀疑OP想让这受文化影响。 - Jon Skeet

8

使用这个作为

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);

是的。const 可以存在于方法(访问器等)的主体内部,也可以是 class(或 struct)的直接成员。如果它在类中,则可以声明为 internalprotectedpublic,以便从其他类中访问。如果从另一个非派生类访问,请使用 NameOfClass.DateFormat 引用 const - Jeppe Stig Nielsen

3

另一个选择是在.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);来实现与使用字符串相同的效果,但是您可以对许多其他格式属性进行更多的控制。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接