天天看点

C# 如何筛选时间串和计算时间差

OTA LOG    SACH/Route Update/Route Update                   05:56:21.105     Channel: 78, Pilot PN: 452

OTA LOG    SRTCH/Route Update/Traffic Channel Complete      05:56:21.437     Channel: 160, Pilot PN: 452

    经常遇到带有如上时间格式的多行字符串,需要计算其中的时间差,直接用心算或者手算,真的很费劲。这种机械性的活当然交给程序来做,是最合适不过的了。

    要计算这种时间差,需要两个步骤:

    1. 从文本行中筛选出特定格式的时间串;

    2. 计算这种时间串的时间差。

    好,先看步骤1:

    怎么筛选呢?哈哈,当然我不会傻到自己再写规则去过滤,这种活,不正好是正则表达式擅长的嘛。

    C#中使用正则表达式,需要先using...

using System.Text.RegularExpressions;

//...

Regex m_regex = new Regex("[0-9]{2}:[0-9]{2}:[0-9]{2}//.[0-9]{3}"); //正则表达式

    下面说如何使用这个正则表达式来筛选出时间字符串:

//我前面已经打开了 fFileReader文件流

string strLineText = fFileReader.ReadLine(); //读取一行文本

Match match = m_regex.Match(strLineText); //使用正则表达式找时间的字符串

if (match.Success)

{

string strTime = match.Value;

//没错,这就筛选出来了

   既然已经筛选出来了,下一步看步骤2,计算时间差,这里我搞了个class:

class TimeDur

{

private string m_strPast = "00:00:00.001";

private string m_strCurrent = "00:00:00.001";

public TimeDur(string strOldTime, string strNewTime)

{

m_strPast = strOldTime;

m_strCurrent = strNewTime;

}

public double GetTimeMinusValue()

{

//从时间字符串创建 DateTime

DateTime dt_old;

DateTime dt_new;

try

{

dt_old = DateTime.Parse(m_strPast);

dt_new = DateTime.Parse(m_strCurrent);

}

catch (System.FormatException fexcep) //不包含有效的日期和时间的字符串形式

{

throw fexcep;

}

//计算两个时间的差

TimeSpan tsValue = dt_new - dt_old;

return tsValue.TotalMilliseconds;

}

}

    有点丑陋,不过能用就行。

    假如我在步骤1已经筛选了2个时间字符串,直接调用这个class计算就行了。

//已经获得时间串

string strPastTime = ...;

string strCurrentTime = ...;

//计算差值

TimeDur timeDur = new TimeDur(strPastTime, strCurrentTime);

double timeminus = timeDur.GetTimeMinusValue(); //OK,差值单位是毫秒

    结语:C#的这个功能还是很实用,而且很简单。我之前也用C++实现过相同的功能,天哪,需要用到boost,非常费劲。为了以后用到相同功能时不至于没地方找代码,特立此存照。