Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use date format as constant in C#?

I'm using "yyyy-MM-dd" several time in the code for date formatting

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

like image 220
Priya Avatar asked Aug 05 '15 05:08

Priya


1 Answers

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();
like image 124
Eric Avatar answered Oct 21 '22 05:10

Eric