简体   繁体   English

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

[英]String was not recognized as a valid DateTime

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. 无法将字符串识别为有效的DateTime。

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

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. 使用指定的格式和特定​​于区域性的格式信息,将日期和时间的指定字符串表示形式转换为其等效的DateTime。 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 . 这是一个DEMO

You can check more Custom Date formats from Custom Date and Time Format Strings 您可以从“ Custom Date and Time Format Strings检查更多“自Custom Date and Time Format Strings

Use DateTime.ParseExact 使用DateTime.ParseExact

since you have this date formatted like 09/04/2013 10:41:45 AM 因为您的日期格式设置为09/04/2013 10:41:45 AM

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

if 09 is day, change the pattern into dd/MM/yyyy hh:mm:ss tt 如果09是一天,则将模式更改为dd/MM/yyyy hh:mm:ss tt

For more information about Date and Time Format Strings, 有关日期和时间格式字符串的更多信息,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM