Home > Mobile >  DateTime formatting option
DateTime formatting option

Time:06-19

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}'";

CodePudding user response:

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.

CodePudding user response:

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");
  • Related