adithyasai adithyasai - 2 months ago 23
C# Question

Print Date in c# in a specified format

I am using the .NET

DateTime
type and would like to print date in the following format


"2017-08-23T11:33:14.653191-05:00"


I am currently able to get the date with year month and day by using this.

DateTime.UtcNow.ToString("yyyy-MM-dd")


The above code results in "2017-08-23", but I want the date in above format.

Answer Source

You can use a custom format string to achieve this by using DateTime Now with a format

DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.ffffffK");

Please see here. Parts of the format string are:

  • yyyy is the four digit year
  • MM the month (numerical)
  • dd the days of the month
  • HH the hours (24 hours format)
  • ss the seconds
  • ffffff the millionths of a second
  • K the time zone