format a date in to the format 'yyyy-mm-dd hh:mm:ss.fff zzz' in csharp

You can use the ToString() method of a .NET DateTime object in combination with a custom date-time format string to format the date into the desired format. Here's an example:

main.cs
// create a DateTime object representing the current date and time
DateTime now = DateTime.Now;

// define the date-time format string
string format = "yyyy-MM-dd HH:mm:ss.fff zzz";

// format the DateTime object using the custom format string and the local time zone
string formattedDateTime = now.ToString(format);

Console.WriteLine(formattedDateTime); // output: 2022-03-22 14:30:45.617 +05:30
398 chars
11 lines

In the above example, we first create a DateTime object representing the current date and time using the DateTime.Now property. Then, we define the date-time format string "yyyy-MM-dd HH:mm:ss.fff zzz" which specifies the format we want: four-digit year, two-digit month, two-digit day, two-digit hour (24-hour clock), two-digit minute, two-digit second, three-digit millisecond, and the time zone offset in the format ±hh:mm.

Finally, we use the ToString() method of the DateTime object to format the date into the desired format, and store the result in a string variable formattedDateTime. We then print the result to the console using Console.WriteLine().

gistlibby LogSnag