将字符串转换为日期 [英] Converting string to date

查看:92
本文介绍了将字符串转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从文本框转换日期。



如果我在本地系统中运行我的网页,它会将字符串转换为日期,但如果我在服务器中运行则无效。 br $>


 DateTime date = DateTime.Parse(txt_date.Text); 





错误消息:字符串未被识别为有效的DateTime 

解决方案

这取决于用户输入文本框的内容:说实话,他可以放任何东西!

这就是为什么我不使用文本框:我建议Calendar [ ^ ]控制:它将以本地用户格式显示,但始终为您提供 SelectedDate [ ^ ]属性,这是一个有效的DateTime,无需进一步转换。


< blockquote> OriginalGriff是完全正确的。有更多类似的选择;请看我过去的答案: TextBox允许仅使用(HH:mm tt)格式使用asp.net [ ^ ]。



-SA


要添加解决方案1和2指出的内容,您还可以使用 DateTime.TryParse() [ ^ ]尝试解析它,如果失败则不会像你一样抛出异常将返回false,然后您可以相应地处理它。


How to convert date from textbox.

If i run my webpage in local system it converting string to date but its not working if i run in server.

DateTime date = DateTime.Parse(txt_date.Text);



error message : String was not recognized as a valid DateTime

解决方案

It's going to depend on what the user enters into the textbox: to be honest, he could put anything!
This is why I don't use textboxes: I would suggest a Calendar[^] control instead: it will display in the local user format, but always give you the SelectedDate[^] property, which is a valid DateTime and needs no further conversion.


OriginalGriff is perfectly right. There are more similar options; please see my past answer: TextBox allow only (HH:mm tt) format using asp.net[^].

—SA


To add to what Solution 1 and 2 have pointed out, you could also use DateTime.TryParse()[^] which attempts to parse it and if it fails then instead of throwing an exception like you are getting it will return a false at which point you can then handle it accordingly.


这篇关于将字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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