繁体   English   中英

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

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

我需要在以下代码中将string转换为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; 
}

这是学习阅读文档的好时机。 我们正在处理DateTime.ParseExact()方法。 这个方法有几个重载,但是我们关心的那个的文档在这里:

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

我通过在 Google 中搜索C# DateTime.ParseExact()找到了该链接。 我去了他的第一个搜索结果,然后单击页面上的第一个链接以找到正确的超载。

我们看到该方法的第二个参数(您提供"D"的地方)是一个格式字符串。 该参数的注释参考备注部分,我们在其中找到:

format参数是一个字符串,它包含一个标准格式说明符,或者一个或多个定义 s 所需格式的自定义格式说明符。 有关有效格式代码的详细信息,请参阅标准日期和时间格式字符串自定义日期和时间格式字符串

按照标准格式字符串的链接,我们终于找到了有关“D”格式的信息:

“D”长日期模式。 2009-06-15T13:45:30 -> 2009 年 6 月 15 日,星期一(美国)

如果没有页面上的完整上下文,这会有点令人困惑,但这告诉您它期望您的dateOfBirth字符串与Monday, June 15, 2009dddd, MMMM dd, yyyy )描述的模式完全匹配 根据上一个问题,您的字符串看起来更像15-06-2009 ( dd-mm-yyyy )。 这些不匹配,这就是您看到错误的原因。

要解决此问题,您需要找到与ParseExact()方法一起使用的格式而不是"D" ,该格式将与输入字符串使用的格式类型完全匹配

同样,这看起来像是一种学习情况,所以我将把它留给你来解决。

正确的代码。

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.

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