Reputation: 4259
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
Upvotes: 5
Views: 4424
Reputation: 7489
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)
}
Upvotes: 0
Reputation: 1502376
Simple steps:
DateTime
. If you know the format to be used, I would suggest using DateTime.ParseExact
or DateTime.TryParseExact
.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
}
Upvotes: 8