[英]How to format this string so that it can be recognized by Convert.ToDateTime?
I am given this whole string from database: 我从数据库给出了这整个字符串:
CCC_0293170118-10-2013-20-27-54.541
I had the substring so that I get 18-10-2013-20-27-54
, but it throws an error 我有子串,所以我得到
18-10-2013-20-27-54
,但它抛出一个错误
I want to convert it to DateTime so that I can compare it with another DateTime with format like "{10/18/2013 8:28:46 PM} to get the time difference. 我想将它转换为DateTime,以便我可以将其与另一个DateTime进行比较,格式为“{10/18/2013 8:28:46 PM}”以获得时差。
You can use "dd-MM-yyyy-HH-mm-ss"
format like; 您可以使用
"dd-MM-yyyy-HH-mm-ss"
格式;
string s = "18-10-2013-20-27-54";
DateTime dt = DateTime.ParseExact(s, "dd-MM-yyyy-HH-mm-ss", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be; 输出将是;
10/18/2013 8:27:54 PM
Here a demonstration
. 这是一个
demonstration
。
A DateTime
doesn't have a format. 一个
DateTime
没有的格式。 It's just a value. 这只是一个价值。
To parse a value such as "18-10-2013-20-27-54" you should use DateTime.ParseExact
(or DateTime.TryParseExact
, if it's somewhat-expected that the data may be invalid). 要解析诸如“18-10-2013-20-27-54”之类的值,您应该使用
DateTime.ParseExact
(或DateTime.TryParseExact
,如果它有点预期数据可能无效)。 So something like: 所以类似于:
DateTime value = DateTime.ParseExact(text, "dd-MM-yyyy-HH-mm-ss",
CultureInfo.InvariantCulture);
It's important to specify the invariant culture here to ensure that the Gregorian calendar is used - if you use the "current system culture" then it could use a different default calendar system. 在此处指定不变文化以确保使用公历是很重要的 - 如果您使用“当前系统文化”,那么它可以使用不同的默认日历系统。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.