C# 如何将时间跨度变量更改为整数类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16607339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:27:09  来源:igfitidea点击:

how to change timespan variable to a integer type?

c#castingtimerdatepickerdynamic-data

提问by Aman Mehrotra

I'm trying to convert timespan variable into an integer variable using 'parse'. I get an error that says:

我正在尝试使用“解析”将时间跨度变量转换为整数变量。我收到一条错误消息:

Format exception was unhandled: Input string was not in correct format

格式异常未处理:输入字符串格式不正确

This is the code is have :

这是代码有:

   private void dateTimePicker4_ValueChanged(object sender, EventArgs e)
    {
        TimeSpan t = dateTimePicker4.Value.ToLocalTime() - dateTimePicker3.Value.ToLocalTime();
        int x = int.Parse(t.ToString());
        y = x;
    }

My target is to display this the change in time for two timepickers, dynamically in a text box, i.e, the difference in minutes between them should be displayed in a textbox automatically.

我的目标是在文本框中动态显示两个时间选择器的时间变化,即它们之间的分钟差应自动显示在文本框中。

采纳答案by Habib

the difference in minutes between them should be displayed in a textbox automatically.

它们之间的分钟差应自动显示在文本框中。

Instead of parsing use TimeSpan.TotalMinutesproperty.

而不是解析使用TimeSpan.TotalMinutes属性。

t.TotalMinutes;

The property is of double type, if you just need to integer part then you can do:

该属性是双精度型,如果您只需要整数部分,则可以执行以下操作:

int x = (int) t.totalMinutes;

回答by Lawrence Wong

 private void dateTimePicker4_ValueChanged(object sender, EventArgs e)
    {
        TimeSpan t = dateTimePicker4.Value.ToLocalTime() - dateTimePicker3.Value.ToLocalTime();
        int x = int.Parse(t.Minutes.ToString());
        y = x;
    }

Have you tried changing it to int x = int.Parse(t.Minutes.ToString());?

您是否尝试将其更改为int x = int.Parse(t.Minutes.ToString());

From : http://msdn.microsoft.com/en-us/library/system.timespan.aspx

来自:http: //msdn.microsoft.com/en-us/library/system.timespan.aspx