c#, date time custom format

in c# how can get the datetime format like below?

yyyy-MM-dd HH:mm:ss.SSS
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dr. KlahnPrincipal Software EngineerCommented:
The default strftime converts a struct tm object to custom textual representation, but it cannot produce fractional seconds.


In this case, the format would be "%F %T"

If the fractional seconds are mandatory, then alternate methods are needed.  See the page below and the code examples below that:


The current local time

#include "tz.h"
#include <iostream>

    std::cout << date::make_zoned(date::current_zone(),
                                  std::chrono::system_clock::now()) << '\n';

system_clock::now() of course gets the current time. It is a de facto standard that this current time is measured in terms of Unix Time which is a very close approximation to UTC. make_zoned pairs the current UTC time with the computer's current local time zone, producing a zoned_time. The zoned_time has a streaming operator so you can easily print it out:

2016-07-05 23:01:05.818378 EDT

Note that the precision of this output is with whatever precision your system_clock::now() supports (microseconds on macOS where I'm writing this).

The current time somewhere else

#include "tz.h"
#include <iostream>

    std::cout << date::make_zoned("Asia/Shanghai",
                                  std::chrono::system_clock::now()) << '\n';

This outputs the current time in Shanghai, for example:

2016-07-06 11:01:05.818378 CST

All IANA timezone names (or links -- aliases to timezones) are supported.

Open in new window

AndyAinscowFreelance programmer / ConsultantCommented:
String s = dt.ToString("yyyy-MM-dd HH:mm:ss.fff");


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Pallavi GodseSr. Digital Marketing ExecutiveCommented:
Please try the following string:

String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.