简体   繁体   English

字符串未被识别为有效的日期时间。 将字符串转换为日期时间

[英]String was not recognized as a valid DateTime. Converting string to DateTime

I need to convert a string to a DateTime format in the following code.我需要在以下代码中将string转换为DateTime格式。 But I am encountering the following error.但我遇到以下错误。 How can I solve this?我该如何解决这个问题?

Unhandled Exception:未处理的异常:

System.FormatException: String was not recognized as a valid DateTime. System.FormatException:字符串未被识别为有效的 DateTime。

public static int calculateAge(string dateOfBirth)
{
    // Implement code here
    int age = 0;  
    DateTime s = DateTime.ParseExact(dateOfBirth, "D", null);
    age = Convert.ToInt32(DateTime.Now.Year - s.Year);  
    if (DateTime.Now.DayOfYear < s.DayOfYear)  
        age = age - 1;  

    return age; 
}

This is a good time to learn to read documentation.这是学习阅读文档的好时机。 We're dealing with the DateTime.ParseExact() method.我们正在处理DateTime.ParseExact()方法。 This method has several overloads, but the documentation for the one we care about is here:这个方法有几个重载,但是我们关心的那个的文档在这里:

https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netcore-3.1#System_DateTime_ParseExact_System_String_System_String_System_IFormatProvider_ https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netcore-3.1#System_DateTime_ParseExact_System_String_System_String_System_IFormatProvider_

I found that link by searching Google for C# DateTime.ParseExact() .我通过在 Google 中搜索C# DateTime.ParseExact()找到了该链接。 I went tot he first search result, and then clicked the first link on the page to find the correct overload.我去了他的第一个搜索结果,然后单击页面上的第一个链接以找到正确的超载。

We see the second argument to that method (where you supplied "D" ) is a format string.我们看到该方法的第二个参数(您提供"D"的地方)是一个格式字符串。 The notes for that argument refer to the Remarks section, where we find this:该参数的注释参考备注部分,我们在其中找到:

The format parameter is a string that contains either a single standard format specifier, or one or more custom format specifiers that define the required format of s. format参数是一个字符串,它包含一个标准格式说明符,或者一个或多个定义 s 所需格式的自定义格式说明符。 For details about valid formatting codes, see Standard Date and Time Format Strings or Custom Date and Time Format Strings .有关有效格式代码的详细信息,请参阅标准日期和时间格式字符串自定义日期和时间格式字符串

Follow the link for the Standard Format Strings, and we finally find this information about the "D" format:按照标准格式字符串的链接,我们终于找到了有关“D”格式的信息:

"D" Long date pattern. “D”长日期模式。 2009-06-15T13:45:30 -> Monday, June 15, 2009 (en-US) 2009-06-15T13:45:30 -> 2009 年 6 月 15 日,星期一(美国)

This is slightly confusing without the full context on the page, but what this tells you is it's expecting your dateOfBirth string to exactly match the pattern described by Monday, June 15, 2009 ( dddd, MMMM dd, yyyy ).如果没有页面上的完整上下文,这会有点令人困惑,但这告诉您它期望您的dateOfBirth字符串与Monday, June 15, 2009dddd, MMMM dd, yyyy )描述的模式完全匹配 Based on the previous question , your strings look more like 15-06-2009 ( dd-mm-yyyy ).根据上一个问题,您的字符串看起来更像15-06-2009 ( dd-mm-yyyy )。 Those don't match, and that's why you see the error.这些不匹配,这就是您看到错误的原因。

To fix this, you need to find a format instead of "D" to use with the ParseExact() method that will exactly match the kind of format used with your input strings.要解决此问题,您需要找到与ParseExact()方法一起使用的格式而不是"D" ,该格式将与输入字符串使用的格式类型完全匹配

Again, this looks like a learning situation, so I'll leave it to you to figure that out.同样,这看起来像是一种学习情况,所以我将把它留给你来解决。

Correct code.正确的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateEx1              //DO NOT CHANGE the namespace name
{
    public class Program       //DO NOT CHANGE the class name
    {
        public static void Main(string[] args)    //DO NOT CHANGE the 'Main' method signature
        {

             Console.WriteLine("Enter the date of birth (dd-mm-yyyy) ");
             string dateOfBirth=Console.ReadLine();
            Console.WriteLine(calculateAge(dateOfBirth));

        }

        public static int calculateAge(string dateOfBirth)
        {
            //Implement code here
            //int age;  
            DateTime s = DateTime.ParseExact(dateOfBirth, "dd-mm-yyyy",null);
            DateTime today = DateTime.Now;
            int year = DateTime.Now.Year;

            int length=dateOfBirth.Length;
            string dcs = dateOfBirth.Substring(6,4);
            string csd=dateOfBirth.Substring(3,2);
            int age2=int.Parse(csd);
            if(age2>=6)
            {
            int age=int.Parse(dcs);
            int age1=(year-1)-age;
            return age1;
            }
            else
            {
                 int age=int.Parse(dcs);
            int age3=(year)-age;
            return age3;
            }
        }

        }

    }  

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

相关问题 字符串日期未被识别为有效的日期时间。 - String date was not recognized as a valid DateTime.' 错误消息为“字符串未被识别为有效的DateTime。” - Error Message as “String was not recognized as a valid DateTime.” 无法将字符串识别为有效的DateTime。 引发异常 - String was not recognized as a valid DateTime. Throws an Exception 错误:字符串未被识别为有效的DateTime。 - Error: String was not recognized as a valid DateTime. 获取错误“字符串未被识别为有效的DateTime”。 - Getting error “String was not recognized as a valid DateTime.” DateTime.ParseExact赋予String未被识别为有效的DateTime。 - DateTime.ParseExact gives String was not recognized as a valid DateTime. 迄今为止的字符串解析错误“字符串未被识别为有效的DateTime。” - String to date parsing error “String was not recognized as a valid DateTime.” 无法将字符串识别为有效的DateTime。 2015年6月26日 - String was not recognized as a valid DateTime. 6-26-2015 “字符串未被识别为有效的DateTime。”Window 7计算机环境中出现错误 - “String was not recognized as a valid DateTime.” Error occur in Window 7 computer environment 无法将字符串识别为有效的DateTime。 “28 \\ 08 \\ 2014” - String was not recognized as a valid DateTime. “28\08\2014”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM