DateTime date = DateTime.Now; DateTimeFormatInfo formatInfo = CultureInfo.CurrentCulture.DateTimeFormat; string formattedDate = date.ToString(formatInfo.ShortDatePattern); Console.WriteLine("Formatted Date: " + formattedDate);
string dateString = "2022-03-15"; DateTimeFormatInfo formatInfo = CultureInfo.CurrentCulture.DateTimeFormat; DateTime date; if (DateTime.TryParseExact(dateString, formatInfo.ShortDatePattern, CultureInfo.CurrentCulture, DateTimeStyles.None, out date)) { Console.WriteLine("Parsed Date: " + date); } else { Console.WriteLine("Invalid Date Format!"); }In this example, we have a date string in the "yyyy-MM-dd" format. We then get the DateTimeFormatInfo for the current culture and specify the expected format using the ShortDatePattern. We then call the DateTime.TryParseExact method and pass in the date string, expected format, and CultureInfo. If the parsing is successful, we print the parsed date to the console, otherwise we print an error message. Overall, the System.Globalization.DateTimeFormatInfo class is a useful tool for formatting and parsing dates and times according to culture-specific rules. It is part of the System.Globalization namespace, which is included in the .NET Framework.