开发者

how to get the three previous dates for the given date .net

I would like to get the 3 dates from the current date or if user enters a date like 16/07/2011 i would like to show the 3 previous dates for this like

15/07/2011,开发者_运维知识库14/07/2011,13/07/2011


Simple steps:

  • Parse the date to a DateTime. If you know the format to be used, I would suggest using DateTime.ParseExact or DateTime.TryParseExact.
  • Use DateTime.AddDays(-1) to get the previous date (either with different values from the original, or always -1 but from the "new" one each time)

For example:

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
}


Just use the TimeSpan object or AddDays function. Here are example extension methods where you can modify days easily:

    public static DateTime SubtractDays(this DateTime time, int days)
    {
        return time - new TimeSpan(days, 0, 0, 0);
    }

    public static DateTime SubtractDays(this DateTime time, int days)
    {
        return time.AddDays(days)
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜