我最近参加了一个关于C#的课程,我真的非常喜欢它,但是我有一个练习,我必须写一个日期,它应该给我一个1000天后的日期。我在研究了DateTime类型之后编写了一些代码,但它总是在1001天而不是1000天之后给我一个日期。另外,我不想在最后的成绩上花时间,所以我真的需要帮助....如果我的主题是愚蠢的话,我想道歉......我刚刚在这里开了一个帐户,这就是我的第一篇文章。 所以这里是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1000DaysAfterBirthV2
{
class Program
{
static void Main(string[] args)
{
string birthDate = Console.ReadLine();
DateTime d = Convert.ToDateTime(birthDate).Date;
DateTime.ParseExact(birthDate, "dd-MM-yyyy", null);
DateTime birthday = DateTime.Parse(birthDate);
DateTime after = birthday.AddDays(1000);
Console.WriteLine(after);
}
}
}
答案 0 :(得分:2)
在特定事件发生后的第五天,我们称之为四天后的日期。下周五是星期一之后的第五天,所以
DateTime friday = monday.AddDays(4);
事件发生后的第一千天也一样。
DateTime after = birthday.AddDays(999);
答案 1 :(得分:2)
至于显示没有时间的日期,请查看.ToString()方法。
after.ToString( "MM/dd/yyyy" );
它类似于你的解析,MM表示月份与mm表示分钟。不同的代表性部分。在输出中选择您想要的任何部分。类似的ToString()应用程序也用于数字字段,例如int,decimal,float来显示前导/尾随零,小数精度等。所有对象都有一个默认的“ToString()”方法,您甚至可以定义自己的方法当你走得太远时,你自己的自定义课程......
澄清
根据您对“after”DateTime变量类型的引用,调用它与上面完全相同。 ToString()返回具有特定格式的字符串。 在调用WriteLine()时,需要一个字符串。由于您传递的是“after”DateTime,因此该方法知道需要调用相应的.ToString()并隐含默认输出。以上所有示例都明确告诉WriteLine打印日期字段“after”,但使用的是SPECIFIC格式。如果您希望以其他格式显示日期,则可以
after.ToString("yyyy-MM-dd") -- year first, then month and day.
after.ToString("dd-MM-yyyy") -- day first, then month, then year
after.ToString("MM-yyyy" ) -- to only show 2-digit month and 4-digit year
答案 2 :(得分:0)
string dateString = Console.ReadLine();
string format= "dd-MM-yyyy";
DateTime result=DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime output = Convert.ToDateTime(result).AddDays(999);
Console.WriteLine(output.ToString("dd-MM-yyyy"));
我认为那样做。 :)