本文介绍了使用Variable TimeSpan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在TimeSpan中使用不同的值,但我无法使其工作。我想要的是这样的:



I need to use different values with a TimeSpan but I cannot get it to work. What I would like is something like this:

TimeSpan mySpan = new TimeSpan();

mySpan = (Convert.ToInt16(DateTime.Parse(DataDoc.SelectSingleNode("/Resource/TimeSteps/TS[24]").InnerText).ToString("HH")), Convert.ToInt16(DateTime.Parse(DataDoc.SelectSingleNode("/Resource/TimeSteps/TS[24]").InnerText).ToString("mm")), 0);





但我不能让它工作,所以如何创建一个名为的变量mySpan并使用以下代码单独更改其变量:?





But I cannot get this to work so how would I create a variable called mySpan and change its variable separately with this code:?

Convert.ToInt16(DateTime.Parse(DataDoc.SelectSingleNode("/Resource/TimeSteps/TS[24]").InnerText).ToString("HH")), Convert.ToInt16(DateTime.Parse(DataDoc.SelectSingleNode("/Resource/TimeSteps/TS[24]").InnerText).ToString("mm")), 0);





谢谢。



Thank you.

推荐答案

DateTime myDate;

if (DateTime.TryParse(DataDoc.SelectSingleNode("/Resource/TimeSteps/TS[24]").InnerText, out myDate) {
   int hours = myDate.Hour;
   int minutes = myDate.Minute;





然后构建你的 TimeSpan



Then construct your TimeSpan:

   TimeSpan ts = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes);
}





编辑:看到OriginalGriff的回答我知道我们星期五晚上会和朋友一起喝啤酒而不是写代码。这是一个更新的,更简单的解决方案:





Seeing OriginalGriff's answer, I realize we're on Friday evening and that I should be drinking beer with friends instead of writing code. Here's an updated, even simpler solution:

if (DateTime.TryParse(DataDoc.SelectSingleNode("/Resource/TimeSteps/TS[24]").InnerText, out myDate) {
   TimeSpan ts = new TimeSpan(myDate.Hour, myDate.Minute, 0);
}


TimeSpan mySpan = new TimeSpan();

string s1 = DataDoc.SelectSingleNode("/Resource/TimeSteps/TS[24]").InnerText;
DateTime dt1 = DateTime.Parse(s1);
short i1  = Convert.ToInt16(dt1.ToString("HH"));
string s2 = DataDoc.SelectSingleNode("/Resource/TimeSteps/TS[24]").InnerText;
DateTime dt2 = DateTime.Parse(s2);
short i2  = Convert.ToInt16(dt2.ToString("mm"));

mySpan = (i1, i2, 0);

你很惊讶它不起作用?最后一点应该是什么?或者呢?编译器不知道,坦白说我也不知道。

如果你想构建一个新的TimeSpan,那么它很简单:

And you are surprised it doesn't work? What is the last bit supposed to be? Or do? The compiler doesn't know, and frankly I have no idea either.
If you mean to construct a new TimeSpan then it's simple:

mySpan = new TimeSpan(i1, i2, 0);

会这样做......

Will do it...


这篇关于使用Variable TimeSpan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 03:53