如何使用“yyyyMMdd Hmm”解析字符串到DateTime格式? [英] How to parse a string to DateTime with "yyyyMMdd Hmm" format?

查看:132
本文介绍了如何使用“yyyyMMdd Hmm”解析字符串到DateTime格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决这个问题我遇到了很大的问题。我试图使用Datetime.ParseExact()解析一个字符串。



我有以下代码:

  DateTime.ParseExact(20151210 832,yyyyMMdd Hmm,CultureInfo.InvariantCulture); 

我收到以下错误:



mscorlib.dll中出现类型System.FormatException的未处理异常其他信息:字符串未被识别为
有效的DateTime。


我做错了什么?如何解决这个问题?



更新:



我也可以得到这样的时间:

  00:01 => 1 
01:00 => 1
01:10 => 10


解决方案

由于 H 说明符可以为2位数,这种方法尝试用 H 83 $ c>说明符。因为没有这样的时间,你会得到 FormatException



对于你的情况,一种防止这种情况的方法是在 8 之前放置一个前导零。

  var s = 20151210 832; 
var result = s.Split('')[0] +0+ s.Split('')[1];
var dt = DateTime.ParseExact(result,yyyyMMdd Hmm,CultureInfo.InvariantCulture);

请注意,这不适用于所有情况。例如,如果您的小时部分已经两位数,如果您的一分钟没有前导零..等。



或者你可以放分隔符为您的所有部分,但在这种情况下,您需要操纵您的字符串和格式。



.NET团队也建议这样做


I'm having huge problems with solving this problem. I'm trying to parse a string using Datetime.ParseExact().

I have the following code:

DateTime.ParseExact("20151210 832", "yyyyMMdd Hmm", CultureInfo.InvariantCulture);

I get following error:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: String was not recognized as a valid DateTime.

What am I doing wrong? How can I solve this problem?

UPDATE:

I can also get times like this:

00:01 => 1
01:00 => 1
01:10 => 10

解决方案

Since H specifier can be 2 digit, this method try to parse your 83 with H specifier. Since there is no such an hour, you get FormatException.

For your case, one way to prevent this is putting a leading zero just before your 8.

var s = "20151210 832";
var result = s.Split(' ')[0] + " 0" + s.Split(' ')[1];
var dt = DateTime.ParseExact(result, "yyyyMMdd Hmm", CultureInfo.InvariantCulture);

Be aware, this will not work for all cases. For example, if your hour part already two digit, if your single minute does not have leading zero.. etc.

Or you can put delimiter for your all parts but in such a case, you need to manipulate both your string and format.

.NET Team suggest this way as well.

这篇关于如何使用“yyyyMMdd Hmm”解析字符串到DateTime格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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