c# - 建议正确的数据类型来存储用户的生日

标签 c# visual-studio-2015

我需要一种方法来whatsUrBirthDay = Console.ReadLine();

我可以轻松地 string whatsUrBirthDay; 但我希望能够存储他们的生日,以便我以后可以“相对”轻松地记忆起它,并可能用它进行计算。

是否存在允许特定格式 MM/DD/YYYY 的数据类型?我假设我可以要求 Month 作为字符串,然后寻找匹配的拼写或数字以 = 一些变量,但肯定有更简单的方法吗?

提前致谢!

编辑 我想补充一点“不”,这不是我选择的变量 - 只是这样做,这样您就会明白我的要求。

最佳答案

最好提示用户以某种特定格式输入日期,让它成为 dd-MM-yyyy 并显示示例以便您可以验证输入并存储到 DateTime多变的;请看下面的代码:

string myDateFormat = "dd-MM-yyyy";
Console.WriteLine("Enter your Birth Date in the format {0} \n (example : {1}) : ",myDateFormat,DateTime.Today.ToString(myDateFormat));
DateTime userBirthday;
if (DateTime.TryParseExact(Console.ReadLine(), myDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out userBirthday))
{
    Console.WriteLine("You lived {0} days from {1} ", (DateTime.Today - userBirthday).TotalDays, userBirthday.ToString(myDateFormat));
}
else
{
    Console.WriteLine("Wrongly formated input");
}

注意:如果输入不是所需的格式,那么 TryParseExact 将返回 false,我们可以显示警告消息

关于c# - 建议正确的数据类型来存储用户的生日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41437515/

相关文章:

c# - 具有不同配置的多个 SignalR 集线器

c# - 从字符串中修剪斜杠#

ASP.net core 1.0 web.config 被覆盖导致 CGI 异常

rdlc - Visual Studio 2015 RC 报告数据窗口丢失

c# - (someDelegateName)?.Invoke(); 中 "?"的用途是什么?

c# - 存储库和查询对象模式。如何实现复杂查询

c# - 使用对象类型作为参数

c# - List 中元组的聚合、求和及乘积

c# - 为什么 'Any CPU (prefer 32-bit)' 允许我在 .NET 4.5 下分配比 x86 更多的内存?

npm - VS2015 的开发人员命令提示符中未将“npm”识别为内部或外部命令错误