我将代码简化为:
string when = "03/03/15 12:00 18:00";
string difference = Convert.ToString(Convert.ToDateTime(when.Substring(when.Length - 5, 5)) - Convert.ToDateTime(when.Substring(when.Length - 10, 10))).substring(difference.Length - 5, 5);
但这仍然很复杂,也行不通:/
基本上,我希望字符串差等于6,因为18-12是6。它需要稍微复杂一点,因为我也想计算分钟数。
我是白痴吗?这简单吗?
只需将您的字符串转换为几个有效值DateTime
,然后减去它们即可。
该Hours
属性将为您提供整个小时的差异表示,在这种情况下为6。
string when = "03/03/15 12:00 18:00";
string[] portions = when.Split(); // 3 items: "03/03/15", "12:00", "18:00"
string yourDateTimeFormat = "MM/dd/yyHH:mm"; // or "dd/MM/yyHH:mm" if the day is first
// create a valid date from 03/03/15 and 12:00
DateTime fromTime = DateTime.ParseExact(
portions[0] + portions[1], yourDateTimeFormat, CultureInfo.CurrentCulture, DateTimeStyles.None);
// create a valid date from 03/03/15 and 18:00
DateTime toTime = DateTime.ParseExact(
portions[0] + portions[2], yourDateTimeFormat, CultureInfo.CurrentCulture, DateTimeStyles.None);
int differenceInHours = (toTime - fromTime).Hours;
根据您对输入的控制程度,您可能希望添加其他逻辑以检查日期是否有效,或者考虑DateTime.TryParseExact
改用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句