Add days, month and year to DateTime in C#

If you want to add any given time span to any date object this is pretty simple. You can add Ticks, Milliseconds, Seconds, Minutes, Hours, Days, Months and Years in a single line statement.

For example if you want to add 5 days to current date time:

DateTime.Now.AddDays(5);

Similarly if you want to add  10 years to current date time:

DateTime.Now.AddYears(10);

and so on for rest of the time spans Milliseconds, Seconds, Minutes, Hours and Months.

Now another thing is you can even add Ticks to any given time in the same way like we added days, years and other time span

DateTime.Now.AddTicks(864000000000);

Above statement will add one day to current date time.

Note: 1 Tick is equal to 100 nanosecond or we can say 1 Tick is equal to one second divided by 10 million.

This is how we can add any time span to DateTime object. Now questions comes in our mind that can we subtract Ticks, Milliseconds, Seconds, Minutes, Hours, Days, Months and Years from any DateTime object in a single line statement like we added them?

Answer is a bug YES. We can subtract DateTime same like we added.

How?

Just add a minus/ hyphen sign (-) just because the number we want to add in same statement.

For example if you want to subtract 5 days from current DateTime:

DateTime.Now.AddDays(-5);

This simple change will do what you want to do. You can use same approach to subtract any of time span that is Ticks, Milliseconds, Seconds, Minutes, Hours, Days, Months and Years.

Leave a Reply