-3

I have a date formatted like this from our database "20230125". How do I turn this string to a date format such as this one "dd/MM/yyyy"

I can probably use insert(4, "/") to add spaces and then turn it into a date. Anyone know of an easier way of implementing something like that?

  • just read the suggestions from the ask-question wizard. Usually you get some pretty decent similar posts for your problem. If those are not appropriate to solve your use-case, please add what you've tried and where the provided solutions fail your needs. – MakePeaceGreatAgain Mar 03 '23 at 21:56
  • Be aware that dates don't have a format. A date is just - well a date - it doesn't care for the **representation**. In other words `"20230125"` and `"2023-01-25"` represent the exact same date, however the *represenation* is different. – MakePeaceGreatAgain Mar 03 '23 at 22:02
  • @MakePeaceGreatAgain - The OP didn't seem to make the mistake that a `DateTime` has a format. The question was all about strings that represent dates. – Enigmativity Mar 03 '23 at 22:23

1 Answers1

0

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
}
Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43