DateTime.ParseExact忽略第一个字符C# [英] DateTime.ParseExact ignore first char C#

查看:95
本文介绍了DateTime.ParseExact忽略第一个字符C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从类似"1140421164500"的设备中获得了一个string值.我必须将其转换为DateTime类型.我想使用DateTime.ParseExact函数.我知道我可以通过手动省略第一个字符来转换它,如下所示:

I get a string value from a device like "1140421164500". I have to convert it to DateTime type. I want to use DateTime.ParseExact function. I know that I can convert it by omitting the first char manually like the following:

DateTime.ParseExact("140421164500", "yyMMddHHmmss", CultureInfo.InvariantCulture);

但是我要避免手动省略第一个字符.我想在ParseExact函数中使用wildcard char忽略它:

But I want to avoid omitting the first char manually. I want to ignore it with a wildcard char in ParseExact function like:

DateTime.ParseExact("1140421164500", "*yyMMddHHmmss", CultureInfo.InvariantCulture);

让我注意,对于夏令时而言,第一个字符可以为1,而对于被动夏令时,则为0.该设备还可以向我发送"0140101000000"之类的信息.

Let me note that the first char can be 1 for daylight saving time is active, or 0 for passive. The device can send me also like "0140101000000".

此功能有类似的东西吗?

Is there anything like that for this function?

推荐答案

There is no wildcard character in custom date and time format that it can parse every possible character in your string.

您可以将格式添加到字符串的第一个字符,例如;

You can add your format the first character of your string like;

string s = "1140421164500";
Console.WriteLine(DateTime.ParseExact(s, s[0] + "yyMMddHHmmss", 
                  CultureInfo.InvariantCulture));

输出为;

4/21/2014 4:45:00 PM

这里是 demonstration .

这篇关于DateTime.ParseExact忽略第一个字符C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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