)DateTime.ParseExact(不按预期工作 - 日期和时间转换在C# [英] Date and time conversion in C# - DateTime.ParseExact() not working as expected

查看:244
本文介绍了)DateTime.ParseExact(不按预期工作 - 日期和时间转换在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有日期/时间格式,例如:  1-MAR-13 92230 根据本文和的 格式此链接如下: D-MMM-YY Hmmss,因为:

I have date/time format, for example: "1-Mar-13 92230" According to this document and this link the format is as follows: "d-MMM-yy Hmmss", because:

Day is single digit, 1-30
Month is 3 letter abbreviation, Jan/Mar etc.
Year is 2 digits, eg 12/13
Hour is single digit for 24 hour clock, eg 9, 13 etc. (no 09)
Minute is standard (eg 01, 52)
Second is standard (eg 30, 02)

我想在我的程序运行下面的code,但我不断收到一个错误字符串未被识别为有效的DateTime。

I'm trying to run the following code in my program, but I keep getting an error of "String was not recognized as a valid DateTime."

string input = "1-Mar-13 92330";
        var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss", 
System.Globalization.CultureInfo.CurrentCulture);

请帮忙,我不是太熟悉,日期时间转换,但我不能看到我已经错在这里。谢谢!

Please help, I'm not too familiar with DateTime conversions, but I can't see where I've gone wrong here. Thanks!

更新:这是因为时间不能之间没有冒号解析? (如1-MAR-13 9时22分30秒得到分析,但我有一个外部数据源,这将是不可能从Hmmss改写为H:MM:SS)

UPDATE: Is this because time cannot be parsed without colons in between? (eg 1-Mar-13 9:22:30 gets parsed, but i have an external data source that would be impossible to rewrite from Hmmss to H:mm:ss)

推荐答案

您可以修复你的约会:

var parts = "1-Mar-13 92230".Split(' ');

if (parts[1].Length == 5)
{
    parts[1] = "0" + parts[1];
}

var newDate = parts[0] + " " + parts[1];

var date = DateTime.ParseExact(newDate, "d-MMM-yy HHmmss",  System.Globalization.CultureInfo.CurrentCulture);

这篇关于)DateTime.ParseExact(不按预期工作 - 日期和时间转换在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆