我从" string
"等设备获得1140421164500
值。我必须将其转换为DateTime
类型。我想使用DateTime.ParseExact
函数。我知道我可以通过手动省略第一个字符来转换它,如下所示:
DateTime.ParseExact("140421164500", "yyMMddHHmmss", CultureInfo.InvariantCulture);
但我想避免手动省略第一个字符。我想在wildcard
函数中使用ParseExact
字符忽略它,如:
DateTime.ParseExact("1140421164500", "*yyMMddHHmmss", CultureInfo.InvariantCulture);
让我注意,第一个char可以是1,夏令时是活动的,0是被动的。该设备也可以发送给我,例如" 0140101000000
"。
这个功能有什么相似的吗?
答案 0 :(得分:8)
custom date and time format中没有通配符,它可以解析字符串中每个可能的字符。
您可以将格式添加到字符串的第一个字符中,如
string s = "1140421164500";
Console.WriteLine(DateTime.ParseExact(s, s[0] + "yyMMddHHmmss",
CultureInfo.InvariantCulture));
输出将是;
4/21/2014 4:45:00 PM
这里有 demonstration
。