我一直在尝试使用 DateTime.ParseExact 来读取我从数据库接收到的日期时间信息。接收到的数据是字符串格式,看起来像这样
"00:10:47:18"
我实现的代码如下:
D = DateTime.ParseExact("00:10:47:18", "dd:HH:mm:ss", null);
其中 D 是 DateTime 类型。但是,我收到一个格式异常,提示无效的字符串格式。我也试过这样做
D = DateTime.ParseExact("00:10:47:18", "'dd':'HH':'mm':'ss'", null);
但即使使用上面的代码也会出现格式异常。任何帮助我指出正确方向的帮助将不胜感激。注意:我在 Unity3D 中执行此操作并在 C# 上进行编码。
最佳答案
您的数据看起来像持续时间,而不是日期/时间。为此,您必须使用 TimeSpan
string input = "00:10:47:18";
TimeSpan output = TimeSpan.ParseExact(input, @"dd\:hh\:mm\:ss", CultureInfo.InvariantCulture);
Unity 不支持 TimeSpan.ParseExact 方法(它是在 .NET 4 中引入的),所以我想你唯一能做的就是手动解析:
public static TimeSpan ParseDuration(string input)
{
string[] inputParts = input.Split(':');
string ddString = inputParts[0];
string hhString = inputParts[1];
string mmString = inputParts[2];
string ssString = inputParts[3];
int dd = int.Parse(ddString, CultureInfo.InvariantCulture);
int hh = int.Parse(hhString, CultureInfo.InvariantCulture);
int mm = int.Parse(mmString, CultureInfo.InvariantCulture);
int ss = int.Parse(ssString, CultureInfo.InvariantCulture);
return new TimeSpan(dd, hh, mm, ss);
}
用法:
string input = "00:10:47:18";
TimeSpan output = ParseDuration(input);
关于c# - DateTime.ParseExact 抛出字符串格式错误 Unity3D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50147653/