简体   繁体   English

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

[英]How to use date format as constant in C#?

I'm using "yyyy-MM-dd" several time in the code for date formatting 我在代码中使用“yyyy-MM-dd”几次进行日期格式化

For example : 例如 :

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

Is it possible to declare the format as constant, so that use of the code again and again can be avoided 是否可以将格式声明为常量,以便可以避免一次又一次地使用代码

Use an extension method without declare any format again and again like this: 使用扩展方法而不是一次又一次地声明任何格式,如下所示:

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

So you use it in this way 所以你以这种方式使用它

var targetdate = Date.ToStandardString();

Use this as 用它作为

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

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

OR 要么

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

Another option that you can do is use the DateTimeFormatInfo overload on .ToString(...) rather than the string overload. 您可以做的另一个选项是使用.ToString(...)上的DateTimeFormatInfo重载而不是string重载。

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

Now you can do var targetdate = DateTime.Now.ToString(MyDateTimeFormatInfo); 现在你可以做var targetdate = DateTime.Now.ToString(MyDateTimeFormatInfo); which is much the same as using string, but you have a lot more control over many other formatting properties. 这与使用字符串非常相似,但您可以更多地控制许多其他格式设置属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM