我有一系列的时间,作为字符串从一个web服务来到我。时间为HH:MM:SS:000 (3毫秒数字)。我需要比较两次,以确定其中一个是否比另一个长两倍以上:
if ( timeA / timeB > 2 )最简单的处理时间字符串的方法是什么?
如果我是用Python编写的话,这将是我问题的答案:两个时间间隔的差异?
(除了我需要的操作符是除法,而不是减法)
编辑:我真正想要的是一种获得timeA / timeB比率的方法,这需要除法,而不是减法。不幸的是,DateTime结构似乎没有除法操作符。更新问题标题和正文以反映这一点。
解决方案:
根据我在下面选择的答案,这是迄今为止提出的所有方法中最简单的一种,下面是工作解决方案:
DateTime timeA;
DateTime timeB;
DateTime.TryParse(webServiceTimeString_A, out timeA);
DateTime.TryParse(webServiceTimeString_B, out timeB);
// TimeA is more than twice the duration of TimeB.
if ( (double)timeA.TimeOfDay.Ticks / (double)timeB.TimeOfDay.Ticks > 2.0f )
{
// Do stuff.
}
else
{
// Do different stuff.
}JavaScript:
最近,这个功能在JavaScript中对于AJAX调用也是必需的,因此,我最终不得不编写一个转换函数(但不是在C#中)。如果需要的话:
if (_timeInSeconds(timeA) / _timeInSeconds(timeB) > 2) {
// Do stuff.
}
// Convert HH:MM:SS:000 string to a number of seconds so we can do math on it.
function _timeInSeconds(stringTime) {
var timeArray = stringTime.split(":");
var timeInSeconds = 0;
//HH
timeInSeconds += (parseInt(timeArray[0], 10) * 3600);
//MM
timeInSeconds += (parseInt(timeArray[1], 10) * 60);
//SS
timeInSeconds += (parseInt(timeArray[2], 10));
//Milliseconds
timeInSeconds += (parseInt(timeArray[3], 10) / 1000);
return timeInSeconds;
}给智者的话:确保指定parseInt的第二个参数.
parseInt(string, 10)...to指定字符串为基-10数字。否则,如果字符串以0 (在HH:MM:SS格式中常见)开头,则JavaScript决定它是一个Base-8数字。这将导致字符串"08"和"09"转换为十进制整数0 (因为Bas-8中不存在8和9),计算被抛出。
发布于 2011-01-11 21:50:16
查看TimeSpan结构,然后查看用.NET计算时间周期
实际上,您的代码可以这样简化:
DateTime timeA = DateTime.Now;
DateTime timeB = DateTime.Now.AddHours(-10.0);
if ( (double)timeA.TimeOfDay.Ticks / (double)timeB.TimeOfDay.Ticks > 2.0f )
Console.WriteLine("Time A is more than twice time B");
else
Console.WriteLine("Time A is NOT more than twice time B");发布于 2011-01-11 21:49:12
首先由解析字符串创建一个解析字符串,然后创建数学很简单 :)
注意,使用-操作符减去两个日期将返回一个TimeSpan,检查MSDN文档中的内容。
发布于 2011-01-11 22:41:05
我认为解析字符串的最简单方法是在TimeSpan.ParseExact 4中使用.Net 4:
public static bool MoreThanDouble(string t1, string t2)
{
const string format = @"%h\:mm\:ss\:fff";
long ticks1 = TimeSpan.ParseExact(t1, format, null).Ticks,
ticks2 = TimeSpan.ParseExact(t2, format, null).Ticks;
return ticks1 - ticks2 > ticks2;
}
static void Main(string[] args)
{
Console.WriteLine(MoreThanDouble("10:11:12:123", "1:23:45:000"));
Console.WriteLine(MoreThanDouble("10:11:12:123", "9:23:45:000"));
}它将打印True False。如果没有.Net 4,可以使用DateTime
public static bool MoreThanDouble2(string t1, string t2)
{
const string format = @"%h\:mm\:ss\:fff";
long ticks1 = DateTime.ParseExact(t1, format, null,
System.Globalization.DateTimeStyles.NoCurrentDateDefault).Ticks,
ticks2 = DateTime.ParseExact(t2, format, null,
System.Globalization.DateTimeStyles.NoCurrentDateDefault).Ticks;
return ticks1 - ticks2 > ticks2;
}https://stackoverflow.com/questions/4663008
复制相似问题