hs2d
hs2d

Reputation: 6199

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?

Upvotes: 2

Views: 1601

Answers (6)

Jakob Christensen
Jakob Christensen

Reputation: 14956

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")

Upvotes: 2

Anthony Pegram
Anthony Pegram

Reputation: 126942

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;

Upvotes: 9

Yochai Timmer
Yochai Timmer

Reputation: 49261

As Anthony said, the subtraction results in a TimeSpan.

TimeSpan accepts a different format:

TimeSpan.ToString Method (String)

Upvotes: 0

James Hill
James Hill

Reputation: 61842

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());

Upvotes: 1

FIre Panda
FIre Panda

Reputation: 6637

Try using

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

Upvotes: 1

izip
izip

Reputation: 2096

Use Stopwatch class.

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

        //code

        sw.Stop();

        sw.Elapsed.ToString();

Upvotes: 0

Related Questions