format a date in to the format 'yyyy-mm-dd' in csharp

To format a date in C# to the format 'yyyy-mm-dd', you can use the ToString() method with a custom format string. Here is an example:

main.cs
DateTime date = DateTime.Now; // replace with your own DateTime variable
string formattedDate = date.ToString("yyyy-MM-dd");
Console.WriteLine(formattedDate); // outputs something like "2022-01-31"
198 chars
4 lines

In the custom format string, "yyyy" represents the year with century as a four-digit number, "MM" represents the month as a two-digit number with a leading zero, and "dd" represents the day of the month as a two-digit number with a leading zero. The hyphens are just character literals to separate the parts of the string. Note that the format string is case-sensitive.

You can also use DateTime.ParseExact() or DateTime.TryParseExact() methods to parse a string in 'yyyy-mm-dd' format into a DateTime object. For example:

main.cs
string dateString = "2022-01-31";
DateTime date;
if (DateTime.TryParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
    Console.WriteLine(date.ToString()); // outputs "1/31/2022 12:00:00 AM" (default format)
}
else
{
    Console.WriteLine("Failed to parse date.");
}
317 chars
11 lines

gistlibby LogSnag