簡體   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