[英]How to parse the date time string including the milliseconds using c#?
I am trying to convert a datatime string "including milliseconds" into a DataTime. 我正在尝试将“包括毫秒”的数据时间字符串转换为数据时间。 I tried tried to use
DateTime.TryParseExact
but it does not give me a milliseconds. 我尝试使用
DateTime.TryParseExact
但它没有给我毫秒。
Here is what I have tired 这是我累的
public static DateTime? dateTimeVal(string raw, string format = null)
{
DateTime final;
if(raw != null){
if( format != null){
string[] formats = new[] { format };
if (DateTime.TryParseExact(raw, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out final))
{
return final;
}
}
if (DateTime.TryParse(raw, out final))
{
return final;
}
}
return null;
}
This is how I use the method above 这就是我使用上述方法的方式
DateTime? dt = dateTimeVal("2016-03-14 11:22:21.352", "yyyy-MM-dd HH:mm:ss.fff");
However, dt gives me this 3/14/2016 11:22:21 AM
但是,dt给了我这个
3/14/2016 11:22:21 AM
How can I get the value to include the milliseconds? 如何获得包含毫秒的值?
DateTime final = new DateTime();
var test = DateTime.TryParseExact("2016-03-14 11:22:21.352", new string[] { "yyyy-MM-dd HH:mm:ss.fff" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
This works for me. 这对我有用。
Just take care for your fff
. 只是照顾你的
fff
。 If you write them uppercase, the milliseconds will be supressed. 如果将它们写为大写,则毫秒数将被忽略。 Lowercase they will be parsed.
小写字母将被解析。
The only thing away from that I can imagine is you have used .ToString
without providing any format. 我能想象的唯一一件事情就是您使用了
.ToString
而不提供任何格式。 Then you'll get: 然后您将获得:
Are you sure you've written the providing format lowercase inside your code? 您确定在代码内部编写了提供格式的小写字母吗? Also have you used
.ToString()
with an output-format that shows up the milliseconds? 您是否也将
.ToString()
与显示毫秒的输出格式一起使用?
If you want to get the DateTime
as string
with milisecond
, then you can use the following code; 如果要使用
milisecond
获取DateTime
作为string
,则可以使用以下代码;
string dateTime = dt.Value.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.