How to get three previous dates for a given .net date

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

15/07/2011,14/07/2011,13/07/2011

+5
source share
2 answers

Simple steps:

  • Divide the date by DateTime. If you know the format to be used, I would suggest using DateTime.ParseExactor 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” every time)

For instance:

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
}
+8
source

TimeSpan AddDays. , :

    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

All Articles