-1

What is the appropriate DateTime formatting option in NET/C# to achieve more efficiently the same as this:

DateTimeOffset dt = <some_date_with_time>;
string dtStr = $"'{dt.Year}/{dt.Month}/{dt.Day} {dt.Hour}:{dt.Minute}:{dt.Second}'";
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • Do you want it exactly like this or shall the format be culture-dependent? – PMF Jun 18 '22 at 15:50
  • 2
    Please make an effort to search this site before posting a new quesstion. In this case, a search for `c# format datetime` found literally [hundreds of results] (https://stackoverflow.com/search?q=%5Bc%23%5D+format+datetime) – Ken White Jun 18 '22 at 15:50
  • 2
    Does this answer your question? [C# DateTime to "YYYYMMDDHHMMSS" format](https://stackoverflow.com/questions/3025361/c-sharp-datetime-to-yyyymmddhhmmss-format) – yousif Jun 18 '22 at 15:53
  • Exactly like that regardless the culture. – cobrajohngs Jun 18 '22 at 18:07
  • I think yes, as "yyyy/MM/dd HH:mm:ss" seems to be the correct option. I am just not sure if it is the correct, and if it will return the same for all cultures. – cobrajohngs Jun 18 '22 at 18:35

2 Answers2

0

DateTime.ToString method is what you looking for. For example:

DateTime dt = DateTime.Now;
string timeStr = dt.ToString(); //it will return full datetime like 06/18/2022 08:07PM

Check this for more formatting options.

Hamid Israfilov
  • 101
  • 1
  • 6
  • Thanks for your response. But what is the right option to return always 2008-10-31 17:04:32 and regardless the culture? – cobrajohngs Jun 18 '22 at 17:45
0
string dtStr = dt.ToString("yyyy/MM/dd HH:mm:ss")

Answering your comment, this is what you need:

DateTime dt = new DateTime(2008, 10, 31, 17, 4, 32);
string timeStr = dt.ToString("yyyy-MM-dd HH:mm:ss");
bmo
  • 66
  • 10