简体   繁体   English

C# DateTime 计算和 ToString

[英]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;其中StrtTime 是: 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 .一个DateTime减去另一个会产生一个TimeSpan值,而不是另一个DateTime The TimeSpan does not support your given format string. TimeSpan不支持您给定的格式字符串。

For standard TimeSpan format strings, see here , and here for custom formats.对于标准TimeSpan格式字符串,请参见此处自定义格式请参见此处。

However, to measure the process time, you should instead use a tool better equipped for the task, System.Diagnostics.Stopwatch .但是,要测量流程时间,您应该改用更适合该任务的工具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 .正如其他人所提到的,您可能想要使用StopWatch However in your particular case you are getting an error because you need to escape ":" when using a formatting string with TimeSpan.ToString .但是,在您的特定情况下,您会遇到错误,因为在使用带有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.使用秒表 class。

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

        //code

        sw.Stop();

        sw.Elapsed.ToString();

As Anthony said, the subtraction results in a TimeSpan .正如安东尼所说,减法产生TimeSpan

TimeSpan accepts a different format: TimeSpan接受不同的格式:

TimeSpan.ToString Method (String) TimeSpan.ToString 方法(字符串)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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