字符串未被识别为有效的DateTime [英] String was not recognized as a valid DateTime

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

问题描述

我的code是:

 保护无效的Page_Load(对象发件人,EventArgs的发送)
    {
        串数值指明MyDate =的Request.QueryString [期间];
        如果(!String.IsNullOrEmpty(数值指明MyDate))
        {
            数值指明MyDate = myDate.Replace(:!);
        }
        日期时间DT1 = Convert.ToDateTime(数值指明MyDate);
        日期时间DT2 = DateTime.Now;
        时间跨度变量= DT2 - DT1;
        如果(variable.TotalMinutes→5)
        {
            的Response.Write(下载时现过期);
        }
        其他
        {
            的Response.Redirect(Default.aspx的假);
        }    }

和我得到的错误,如:


  

字符串未被识别为有效的DateTime。



解决方案

使用尝试 DateTime.ParseExact() 方法;


  

指定字符串重新日期和时间为presentation其转换
  日期时间相当于使用指定的格式和区域性特定
  格式的信息。 字符串重新presentation的格式必须匹配
  指定格式完全相同。


 日期时间日期= DateTime.ParseExact(数值指明MyDate,DD / MM / YYYY HH:MM:SS TT,CultureInfo.InvariantCulture);

下面是一个 DEMO

您可以查看更详细的自定义日期格式从 自定义日期和时间格式字符串

My code is:

 protected void Page_Load(object sender, EventArgs e)
    {
        string myDate = Request.QueryString["period"];
        if (!String.IsNullOrEmpty(myDate))
        {
            myDate = myDate.Replace("!", ":");
        }
        DateTime dt1 = Convert.ToDateTime(myDate);
        DateTime dt2 = DateTime.Now;
        TimeSpan variable = dt2 - dt1;
        if (variable.TotalMinutes > 5)
        {
            Response.Write("Download time is expired now");
        }
        else
        {
            Response.Redirect("Default.aspx", false);
        }



    }

and I'm getting error like:

String was not recognized as a valid DateTime.

解决方案

Try with DateTime.ParseExact() method;

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

DateTime date = DateTime.ParseExact(myDate, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Here is a DEMO.

You can check more Custom Date formats from Custom Date and Time Format Strings

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

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