字符串不是有效的日期时间C# [英] String is not valid date time C#

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

问题描述

string d = Request.Form["StartDate"];
DateTime dt = Convert.ToDateTime(d);
 string e = Request.Form["EndDate"];
 DateTime ed = Convert.ToDateTime(e);
objCoupons.EndDate = ed;
objCoupons.StartDate = dt;





这是我的代码。

d的值格式为dd / mm / yyyy,例如。 10月10日。

转换为日期时,它会抛出一个错误

将strig转换为datetime时将字符串解析为将每个变量放入datetime对象之前的日期。



我尝试了什么:



i尝试使用日期时间解析

或其他转换事物和不变文化等等



this is my code .
the value of d is in format dd/mm/yyyy eg. 10/10/2017.
while converting to date time it throws an error that
when converting strig to datetime parse the string to take date before putting each variable to datetime object.

What I have tried:

i have tried using datetime parse
or another convert thing and invariant culture etc etc

推荐答案

使用 DateTime.TryParseExact Method(System) [ ^ ]



use DateTime.TryParseExact Method (System)[^]

string strDate = "10/10/2017";
         DateTime dtTarget = default(DateTime); // (or) DateTime.MinValue , use this for comparision
         if (DateTime.TryParseExact(strDate, "dd/mm/yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out dtTarget))
         {
             // use the  dtTarget object to get the parsed dates
         }
         else {
             // show the error message
         }


如果您知道字符串始终以特定格式格式化,请使用 DateTime.ParseExact Method(String,String,IFormatProvider)(System) [ ^ ]或 DateTime.TryParseExact 方法。



如果您知道创建字符串时使用的区域性设置,请使用 DateTime.Parse方法(系统) [ ^ ]或接受文化信息参数的相应 TryParse 方法。



在所有其他情况下,无法将字符串转换为日期。



为避免日期转换问题,请尽可能以二进制格式存储它们或使用定义的格式(固定或存储/传递作为附加参数)。
If you know that the string is always formatted in a specific format use the DateTime.ParseExact Method (String, String, IFormatProvider) (System)[^] or the DateTime.TryParseExact method.

If you know the culture settings that has been used when creating the string, use one the DateTime.Parse Method (System)[^] or the corresponding TryParse methods that accepts a culture info parameter.

In all other cases it not possible to convert strings to dates.

To avoid date conversion problems store them in binary format whenever possible or use a defined format (fixed or stored/passed as additional argument).


这篇关于字符串不是有效的日期时间C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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