如何转换"时间"从日期时间转换成int? [英] How to convert the "time" from DateTime into int?

查看:444
本文介绍了如何转换"时间"从日期时间转换成int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些以小时为单位的几个值的DataGrid和我想知道:

I have a DataGrid which contains a few values that are in hours and I wanted to know:

如何从我的DataGrid中得到的只是时间,并转换成一个int(或双)变量。

How to get ONLY the time from my DataGrid and convert it into an int (or double) variable.

我的目标是与我的DataGrid时间值的一些操作,想将号码加入进去。

My goal is to do a few operations with my DataGrid time values, like to add numbers into it

例如:
使用我的dataGridView1.Rows [1] .Cells [2] .Value.ToString();它会显示一个DateTime值(这是我的DataGrid中),这个值,我想过滤器只有时间从这个并将其转换成一个int

EXAMPLE: Using my "dataGridView1.Rows[1].Cells[2].Value.ToString();" It'll show a DateTime value (which is inside my DataGrid), with this value, I wanna filter ONLY the time from this and convert it into an int

部分我的代码,我想捕获时间:

the part of my code which I wanna "capture" the time:

txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value.ToString(); 
string value = dataGridView1.Rows[0].Cells[2].Value.ToString(); 
lblLeft.Text = value.Split(' ')[1]; 



我想要得到的价值(这是从DataGrid datetime值),并将其转化为。一个int

I wanna get the "value" (which is a DateTime value from the DataGrid) and convert it into an int.

请注意:
- 在我的数据网格对我来说,迄今为止,它是不相关的,我只需要挑时间(是的,我知道,我不能拆的日期时间分别做他们)

note: - The date for me in my dataGrid it's not relevant, I only have to pick the time (and yes, I know that I can't "split" DateTime to do them separately)

推荐答案

第一步是字符串转换为DateTime。使用DateTime.TryParse(字符串值,日期时间出来DT)。然后,当马修·沃森建议正确,得到变量DT的值转换为使用dt.TimeOfDay.TotalMilliseconds毫秒。另外,也可以向跨度转换在TotalSeconds或TotalMinutes它是否适合您的要求。
,尽量避免直接检查如果单元格值为null之前调用ToString()方法。如果我想避免的检查,我会做的编译器做使用类似:行[3] .Cells [2] .value的+,而不是Value.ToString()

First step is to convert string to DateTime. Use DateTime.TryParse(string value, out DateTime dt). Then as Mathew Watson rightly suggested, get the value of variable dt converted to milliseconds using dt.TimeOfDay.TotalMilliseconds. It is also possible to convert the span in TotalSeconds or TotalMinutes if it suits your requirement. Try to avoid calling ToString() method directly before checking if cell value is null. If I want to avoid the check, I would make compiler to do it by using something like : Rows[3].Cells[2].Value + "" instead of Value.ToString().

这篇关于如何转换"时间"从日期时间转换成int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆