【问题标题】:Is DateTime.Now.AddHours(custom) possible? [closed]DateTime.Now.AddHours(custom) 可能吗? [关闭]
【发布时间】:2013-10-02 10:37:03
【问题描述】:

我只是想知道这是否可能:

int custom = Console.ReadLine(); //or string custom?
Console.WriteLine(DateTime.Now.Add(custom);

我知道Console.ReadLine() 等于string。但尽管如此,我确信这在某种程度上是可能的。谷歌帮不了我,所以我想我会是第一个问的。 (或者我只是不擅长搜索)

【问题讨论】:

  • 您的问题与DateTime.Now.AddHours 无关——值得关注您面临的非常具体的问题,即从stringint 的转换。
  • 您的意思是从Console.ReadLine();DateTime?我知道我必须对其进行转换,但每次尝试我都会遇到错误。嗯,我要去看看这个。谢谢。
  • 不,给int。您的第一行无法编译,并且与 DateTime 没有任何关系。
  • 这只是一个简单的例子。我知道它不应该是int
  • 为什么不是int?成为int 非常有意义。如果你希望它是int,你应该说出你想要想要什么,否则你就是在浪费人们回复你的时间。跨度>

标签: c# string datetime console int


【解决方案1】:

您可以将ReadLine() 结果解析为int

int custom = 0;
if(int.TryParse(Console.ReadLine(), out custom)) {
  Console.WriteLine(DateTime.Now.AddHours(custom));
}
else {
  Console.WriteLine("Invalid number!");
}

【讨论】:

    猜你喜欢
    • 2012-05-18
    • 2014-09-05
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 2013-02-23
    • 2011-03-04
    • 1970-01-01
    • 2014-08-01
    相关资源
    最近更新 更多