none
DateAdd function in c#

    Question

  • I have a function

    DateAdd(DateInterval.Day, -1, date2Display)  in VB , i need help in converting to c#.

    Any suggestions.

    Friday, October 16, 2009 1:17 PM

Answers

  • Why not just use Operators to add Date and Timespan ?

    DateTime dt1 = DateTime.Now;

     

    TimeSpan oneDay = new TimeSpan(1, 0, 0, 0);

     

    DateTime tomorrow = dt1 + onyDay;

    Doesn't that look nice ?
    Beside adding days, you have to keep in mind, as long as you add only days, hours, minutes, seconds, you are adding a definite timespan.
    It's always a constant number of Nanoseconds.

    This is why the largest unit of a TimeSpan object is the day.

    As soon as you start adding months and years, the duration depends on the actual starting point. Each month has different number of days, each year has diffent number of days.

    That's why for Adding a Month or a Year, you have to use the AddYear and AddMonths months, of the DateTime structure.
    It doesnt' work with Timespans or operators, because it depends on the starting point in time.
    The AddDays method ist there more or less for completeness in the list of these functions.

    • Marked as answer by sam581 Monday, October 19, 2009 11:55 AM
    Saturday, October 17, 2009 11:22 AM

All replies

  • You can use AddDays method of DateTime object:

    date2Display=date2Display.AddDays(-1);

    • Proposed as answer by SYSTEM.IO Friday, October 16, 2009 1:48 PM
    Friday, October 16, 2009 1:20 PM
  • Following MSDN code should help
    // Calculate what day of the week is 36 days from this instant.
    System.DateTime today = System.DateTime.Now;
    System.TimeSpan duration = new System.TimeSpan(36, 0, 0, 0);
    System.DateTime answer = today.Add(duration);
    System.Console.WriteLine("{0:dddd}", answer);
    Friday, October 16, 2009 7:56 PM
  • Why not just use Operators to add Date and Timespan ?

    DateTime dt1 = DateTime.Now;

     

    TimeSpan oneDay = new TimeSpan(1, 0, 0, 0);

     

    DateTime tomorrow = dt1 + onyDay;

    Doesn't that look nice ?
    Beside adding days, you have to keep in mind, as long as you add only days, hours, minutes, seconds, you are adding a definite timespan.
    It's always a constant number of Nanoseconds.

    This is why the largest unit of a TimeSpan object is the day.

    As soon as you start adding months and years, the duration depends on the actual starting point. Each month has different number of days, each year has diffent number of days.

    That's why for Adding a Month or a Year, you have to use the AddYear and AddMonths months, of the DateTime structure.
    It doesnt' work with Timespans or operators, because it depends on the starting point in time.
    The AddDays method ist there more or less for completeness in the list of these functions.

    • Marked as answer by sam581 Monday, October 19, 2009 11:55 AM
    Saturday, October 17, 2009 11:22 AM