错误:字符串未被识别为有效的日期时间 [英] Error: string was not recognized as a valid datetime

查看:285
本文介绍了错误:字符串未被识别为有效的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好......

我正在创建一个项目,每当我遇到错误时我需要将文本框值转换为日期时间..以下是我的代码。



我尝试了什么:



Hi Everyone...
I am creating a project where i need to convert text box value into date time every time i have faced an error.. below is my code.

What I have tried:

public int Validate_DOB()
   {
       DateTime dt = DateTime.Parse(txt_DOB.Text);//error occured at this line of code
       int Validate = DateTime.Now.Year - dt.Year;
       return Validate;
   }

推荐答案

你应该使用 DateTime.TryParse [ ^ ]

或者,考虑使用datatimepicker让用户选择日期而不是允许自由格式文本的文本框。看看这个:使用jQuery插件在ASP.Net中实现DateTimePicker [ ^ ]
You should use DateTime.TryParse[^]
Alternatively, consider using a datatimepicker to let users select a date rather than a text box that allow free form text. Check this out: Implement DateTimePicker in ASP.Net using jQuery Plugin[^]


嗨Aamir,



从错误消息中可以看出错误消息 - 中的值文本框不是日期时间。你可以像Peter建议的那样使用 TryParse()。或者你可以捕获一个 FormatException 让用户在运行时知道这个问题。

Hi Aamir,

The error is clear from the error msg - the value in the text box is not a datetime. You can use TryParse() as Peter suggested. Or you can catch a FormatException to let the user know about the problem at runtime.
try
{
    DateTime dt = DateTime.Parse(txt_DOB.Text);//error occured at this line of code
    int Validate = DateTime.Now.Year - dt.Year;
}
catch (FormatException)
{
    MessageBox.Show("This is not a valid date time.");
}


这篇关于错误:字符串未被识别为有效的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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