我想从当前日期开始获取 3 个日期,或者如果用户输入像 16/07/2011
这样的日期,我想显示之前的 3 个日期
15/07/2011,14/07/2011,13/07/2011
最佳答案
简单步骤:
- 将日期解析为
DateTime
。如果您知道要使用的格式,我建议您使用DateTime.ParseExact
或DateTime.TryParseExact
。 - 使用
DateTime.AddDays(-1)
获取上一个日期(使用与原始日期不同的值,或者始终为 -1 但每次都来自"new"日期)
例如:
string text = "16/07/2011";
Culture culture = ...; // The appropriate culture to use. Depends on situation.
DateTime parsed;
if (DateTime.TryParseExact(text, "dd/MM/yyyy", culture, DateTimeStyles.None,
out parsed))
{
for (int i = 1; i <= 3; i++)
{
Console.WriteLine(parsed.AddDays(-i).ToString("dd/MM/yyyy"));
}
}
else
{
// Handle bad input
}
关于c# - 如何获取给定日期的前三个日期.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6715924/