2015-11-26 66 views
3

下面这段代码给我下面的错误:难点解析字符串为DateTime

"Unhandled Exception: string was not recognized as a valid DateTime.

有一个未知的词开始在索引0”

我如何将字符串转换为DateTime正确?这里

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

namespace Exercise 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.Write("Enter your birthday in format(dd.mm.yyyy): "); 
      DateTime userBirthday = DateTime.Parse(Console.ReadLine()); 
      long result = DateTime.Today.Subtract(userBirthday).Ticks; 
      Console.WriteLine("You are {0} years old.", new DateTime(result).Year - 1); 
      Console.WriteLine("After 10 years you will be {0} years old.", new DateTime(result).AddYears(10).Year - 1); 
     } 
    } 
} 
+2

使用'DateTime.TryParse' /'DateTime.TryParseExact'如果你得到用户输入。除此之外,用户给你什么作为输入?您当前的日期设置是什么(控制面板/区域和语言)。 –

回答

1

DateTime.Parse使用您的CurrentCulture设置的标准日期和时间格式默认为。看起来像dd.mm.yyyy不是其中之一。

您可以使用DateTime.ParseExactDateTime.TryParseExact方法精确地指定您的格式。

顺便说一句,我强烈怀疑你的意思MM(数月),而不是mm(分)。

DateTime userBirthday = DateTime.ParseExact(Console.ReadLine(), 
              "dd.MM.yyyy", 
              CultureInfo.InvariantCulture); 

顺便说一句,计算年龄在编程上很困难,因为它取决于你出生的地方和你现在在哪里。

检查:Calculate age in C#

5

您可以使用ParseExact以当日指定格式:

DateTime userBirthday = DateTime.ParseExact(Console.ReadLine(), "dd.MM.yyyy", CultureInfo.InvariantCulture) ; 

或者TryParseExact如果您don'trust用户输入:

DateTime userBirthday ; 

if (!DateTime.TryParseExact(Console.ReadLine(), "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out userBirthday)) 
{ 
    Console.WriteLine("You cheated") ; 
    return ; 
} 

可用DateTime格式可以发现here