【问题标题】:C# Console App || Can i use ddMMyy as DayTime instead of dd/MM/yy? [duplicate]C# 控制台应用程序 ||我可以将 ddMMyy 用作 DayTime 而不是 dd/MM/yy 吗? [复制]
【发布时间】:2020-02-23 05:27:38
【问题描述】:

我要求用户输入不含/- 的6 位生日。如何定义日期时间读取6位数字ddMMyy??

WriteLine("Write Your birthday using unly number and 6 digits 'ddMMyy'")
string userinput = ReadLine();
DateTime bday = DateTime.Parse(userinput);
WriteLine($"Your birthday is: {bday}");

输出:

未处理的异常。 System.FormatException:字符串“041197”不是 被识别为有效的 DateTime。

不,它不是重复的。这没有回答我的问题“stackoverflow.com/questions/15738608/...” 但是这篇文章的答案解决了它!

【问题讨论】:

  • 欢迎来到 Stack Overflow。在这种情况下,您可能想使用ParseExact 和/或TryParseExact 方法,例如DateTime bday = DateTime.ParseExact("041197", "ddMMyy", CultureInfo.InvariantCulture);
  • 谢谢。我的用户输入是'041197'。 04 是日,11 是月,97 是年。
  • @maytham-ɯɐɥʇʎɐɯ 谢谢我去看看..你的评论去哪儿了? :D
  • 使用ParseExact。查看链接的副本。
  • 别忘了添加System.Globalization命名空间。

标签: c# datetime console-application


【解决方案1】:

试试这个:

    using System;
    using System.Globalization;
    public class Test
    {
    public static void Main()
    {       
        CultureInfo provider = new CultureInfo("en");
        DateTime dt =   DateTime.ParseExact("040415","ddMMyy", provider);
  Console.WriteLine(dt.Year.ToString());
    }
}

【讨论】:

  • 完美解决了我的问题。非常感谢:)
【解决方案2】:
 CultureInfo info= new CultureInfo("en");
 DateTime birthDay=   DateTime.ParseExact("041197","ddMMyy", info);
 WriteLine($"Your birthday is: {birthDay}");

【讨论】:

  • 只有代码的答案通常被认为是低质量的。您能否为您的答案添加解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-01
  • 2011-11-23
相关资源
最近更新 更多