How to use date format in c #?

I use "yyyy-MM-dd" several times in the code to format the date

For example:

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

Is it possible to declare the format as permanent so that the code can be used again and again

+7
tostring date c # datetime
source share
3 answers

Use it 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); 
+6
source share

Use the extension method without declaring it 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 that way

 var targetdate = Date.ToStandardString(); 
+8
source share

Another option you can do is to overload DateTimeFormatInfo with .ToString(...) and not overload 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); which is almost the same as using a string, but you have a lot more control over many other formatting properties.

+2
source share

All Articles