简体   繁体   中英

C# DateTime calculation and ToString

Im doing simple calculation with time, to see how long the process has been running.

(DateTime.Now - StrtTime).ToString("hh:mm:ss")

Where StrtTime is: DateTime StrtTime = DateTime.Now; . But im getting an exception:

Input string was not in a correct format.

Whats the proper way to do this?

One DateTime subtracting another results in a TimeSpan value, not another DateTime . The TimeSpan does not support your given format string.

For standard TimeSpan format strings, see here , and here for custom formats.

However, to measure the process time, you should instead use a tool better equipped for the task, System.Diagnostics.Stopwatch .

Stopwatch watch = new Stopwatch();
watch.Start();

DoSomeProcess();

watch.Stop();
TimeSpan processTime = watch.Elapsed;

As others have mentioned you may want to use StopWatch . However in your particular case you are getting an error because you need to escape ":" when using a formatting string with TimeSpan.ToString . Try this:

(DateTime.Now - StrtTime).ToString(@"hh\:mm\:ss")

Try using

Stopwatch stpWatch1 = new Stopwatch();
            stpWatch1.Start();
            .............
            stpWatch1.Stop();
TimeSpan ts = stpWatch1.Elapsed;// it also contains stpWatch1.ElapsedMilliseconds

As Anthony mentioned, Stopwatch would be better suited for this task. To answer your question though, you can format the Date like this:

String.Format("{0:hh:mm:ss}", (DateTime.Now - StrtTime).ToString());

Use Stopwatch class.

        Stopwatch sw = new Stopwatch();
        sw.Start();

        //code

        sw.Stop();

        sw.Elapsed.ToString();

As Anthony said, the subtraction results in a TimeSpan .

TimeSpan accepts a different format:

TimeSpan.ToString Method (String)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM