我将在代码中多次使用"yyyy-MM-dd"进行日期格式化。
例如:
var targetdate = Date.ToString("yyyy-MM-dd");
是否可以将格式声明为常量,从而避免反复使用代码?
使用扩展方法时不需要一遍又一遍地声明任何格式,就像这样:
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();
使用这个作为
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
)的直接成员。如果它在类中,则可以声明为 internal
、protected
或 public
,以便从其他类中访问。如果从另一个非派生类访问,请使用 NameOfClass.DateFormat
引用 const
。 - Jeppe Stig Nielsen另一个选择是在.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);
来实现与使用字符串相同的效果,但是您可以对许多其他格式属性进行更多的控制。