Datetime is giving error while conversion

烂漫一生 提交于 2020-01-03 19:08:18

问题


I have string in this formate : 19/8/1988

note: String DateOfBirth=" 19/8/1988"

When i use Datetime.parse(DateOfBirth) it gives me invalid dateformat error.

I am also unable to do it in cdate(DateOfBirth)

When i enters string in format mm/dd/yyyy i.e. 8/19/1988 then it does not gives me error.

Please help me to convert string into date in mm/ddd/yyyy format.


回答1:


Lowercase mm means minute instead of month, you need to use uppercase M(single character).

But you also need to use ParseExact with CultureInfo.InvariantCulture. Otherwise your current culture is used to get the date separator which is not necessarily /(in many countries it is .).

So this works with any culture:

DateTime.ParseExact("19/8/1988", "dd/M/yyyy", CultureInfo.InvariantCulture)

Demo

The "/" Custom Format Specifier

If you want to validate a given date-string you can use DateTime.TryParseExact:

DateTime dt; 
if(DateTime.TryParseExact("19/8/1988", "dd/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) 
{
    // success, dt contains the correct date now
} 
else 
{
    // not a valid date 
}



回答2:


Note that you have space before the date time, you need to remove that string before parse to DateTime using given format

var date = DateTime.ParseExact(DateOfBirth.Trim(), "d/M/yyyy", CultureInfo.InvariantCulture);

if you have multiple date time formats then

var date = DateTime.ParseExact(DateOfBirth.Trim(), new string[] {"d/M/yyyy","M/d/yyyy"} , CultureInfo.InvariantCulture, DateTimeStyles.None);



回答3:


Net developer, here is a code its in vb and needs to be converted to C#

Dim time As DateTime = DateTime.Now
Dim format As String = "dd/MM/yyyy" 
' you can set format to both "dd/MM/yyyy" or "d/MM/yyyy"

MsgBox(time.ToString(format))

let me know if it helps.




回答4:


I know what cause for you error, system datetime default taking as US datetime format (mm/dd/yyyy) change this format in your system, goto control panel --> regional and languages --> formats --> additional settings--> date to change your desired format this is manually solved your problem or otherwise programmatically solved this way

DateTime.ParseExact("19/8/1988", "dd/M/yyyy", CultureInfo.InvariantCulture)


来源:https://stackoverflow.com/questions/18461272/datetime-is-giving-error-while-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!