DateTime.TryParseExact
method converts the specified string representation of a date and time to its DateTime
equivalent. The format of the string representation must match a specified format exactly. The method returns a value that indicates whether the conversion succeeded.
DateTime.ToString
method converts the value of the current DateTime
object to its equivalent string representation using the specified format and the formatting conventions of the current culture.
A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation.
The "yyyy" custom format specifier represents the year with a minimum of four digits. The "MM" custom format specifier represents the month as a number from 01 through 12. The "dd" custom format string represents the day of the month as a number from 01 through 31.
So you can use format yyyyMMdd
to parse your string from DB and dd/MM/yyyy
format to convert DateTime
object back to string with expected format.
string dateString = "20230125";
if (DateTime.TryParseExact(dateString, "yyyyMMdd", null, System.Globalization.DateTimeStyles.None, out var dateValue))
{
string formattedDate = dateValue.ToString("dd/MM/yyyy");
Console.WriteLine(formattedDate); // Output: 25/01/2023
}