Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.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

like image 304
Vivekh Avatar asked Jul 16 '11 07:07

Vivekh


People also ask

How to get previous date of given date in C#?

To display the previous day, use the AddDays() method and a value -1 to get the previous day.

How do you get the day before a DateTime?

<DateTime>. Date. AddDays(-1); This will strip off the time and give you midnight the previous day.

How to get day name from date in C# net?

Extract the full weekday name using System; using System. Globalization; public class Example { public static void Main() { DateTime dateValue = new DateTime(2008, 6, 11); Console. WriteLine(dateValue. ToString("dddd", new CultureInfo("es-ES"))); } } // The example displays the following output: // miércoles.

How can I get the last date of a previous month in C#?

Day); DateTime endDate = startDate. AddMonths(1). AddDays(-1);


1 Answers

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
}
like image 107
Jon Skeet Avatar answered Sep 28 '22 03:09

Jon Skeet