c# - DateTime.ParseExact 抛出字符串格式错误 Unity3D

标签 c# datetime unity3d datetime-format

我一直在尝试使用 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/

相关文章:

asp.net - PC 区域和语言设置在 .Net 中被忽略

c# - 如何在 OSX 上使用 C# 运行 shell 脚本?

c# - VS2015自动完成功能不起作用

unity3d - 错误(86,9): BCE0044: expecting EOF, found 'case'

c# - 空条件运算符不适用于泛型方法中的 Func<T>

c# - .NET Core MailKit SMTP AUTH LOGIN 作为本地 linux 帐户

c# - 为什么那个异常管理代码很臭?

c# - 为什么 Ping 超时无法正常工作?

javascript - 获取 UTC 月份时月份不正确

mysql - 将日期更改为商业日期 MyS