SS字符串转换为HH

SS字符串转换为HH

本文介绍了在C#中将MM:SS字符串转换为HH:MM:SS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,可以很好地将HH:MM:SS转换为整数秒.

I have this piece of code which works nicely to convert HH:MM:SS to seconds as an integer.

  for (int i = 0; i < nrdaily.Rows.Count; i++)
  {
      double NRT = TimeSpan.Parse(nrdaily.Rows[i][3].ToString()).TotalSeconds;
      nrdaily.Rows[i][3] = NRT;
  }

但是,我正在处理一个CSV文件,其中一个字段包含许多以MM:SS格式存储的值,而TotalSeconds似乎将其误解为HH:MM并给出了错误的结果.

However, I have a CSV file I'm dealing with where a field has many values that are stored in MM:SS format and TotalSeconds seems to misinterpret it as HH:MM and gives a false result.

如何检查字符串是否为HH:MM:SS格式,以及是否为MM:SS并将其转换为HH:MM:SS?

How could I check the string to see if it's in HH:MM:SS format, and if it is in MM:SS convert it to HH:MM:SS?

推荐答案

您可以检查启动程序的字符串长度以标识格式.

You could check the string length for starters to identify the format.

for (int i = 0; i < nrdaily.Rows.Count; i++)
{
     string time = nrdaily.Rows[i][3].ToString();
     if (time.Length == 5)
          time = "00:" + time;
     double NRT = TimeSpan.Parse(time).TotalSeconds;
     nrdaily.Rows[i][3] = NRT;
}

检查长度是一种非常简单的方法.为了更准确地识别格式,您可以使用正则表达式.

Checking length is a very simplistic approach. To identify the format more accurately, you could use regular expressions.

这篇关于在C#中将MM:SS字符串转换为HH:MM:SS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 23:05