当格式为dd / mm / yyyy的日期而不是日期时间时,代码失败 [英] Code fails when date in the format dd/mm/yyyy is given instead of date time

查看:81
本文介绍了当格式为dd / mm / yyyy的日期而不是日期时间时,代码失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DateTime.ParseExact(value[54].Trim(), "d/M/yyyy", CultureInfo.InvariantCulture);







当日期格式为dd / mm / yyyy而不是日期时间时代码失败。



之前有人遇到过这个问题吗?



我尝试了什么:






the code fails when date in the format dd/mm/yyyy is given instead of date time.

Any one faced this issue before?

What I have tried:

DateTime.ParseExact(value[54].Trim(), "d/M/yyyy", CultureInfo.InvariantCulture);

推荐答案

您的日期格式字符串不准确。看看这个 [ ^ ]格式字符串的页面。 />


为了满足多种日期格式,您应该选择 TryParseExact 。它接受不同格式的字符串数组。
You date format string is not accurate. Take a look at this[^] page for format strings.

In order to cater for multiple date formats, you should go for TryParseExact. It accepts an array of strings for different formats.


使用'DateTime'类的'ParseExact'方法和'dd / MM / yyyy'格式,它也适用于'd / M / yyyy'。

见下面的代码片段

Use 'ParseExact' method of 'DateTime' class with 'dd/MM/yyyy' format, it also work for 'd/M/yyyy'.
see below snippet
string dt = "24/12/2010";
DateTime dt1;
//always use InvariantCulture for dateformat provider as it support large number of customized datetime formats
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
dt1 = DateTime.ParseExact(dt, "dd/MM/yyyy", provider);
MessageBox.Show("String successfully converted to DateTime" + dt1.Year);  





希望有帮助

了解更多细节看到这个 [ ^ ]


按照建议,使用TryParseExact并传递一个您接受的格式列表,然后添加一些代码,当字符串不是您接受的格式时处理。



DateTime.TryParseExact Method(String,String [],IFormatProvider,DateTimeStyles,DateTime)(System) [ ^ ]
As suggested, use TryParseExact and pass it a list of formats you accept, then add some code that handles when the string isn't in a format you accept.

DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) (System)[^]


这篇关于当格式为dd / mm / yyyy的日期而不是日期时间时,代码失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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