GuruKulki
GuruKulki

Reputation: 26418

substract day in date in c#?

I want to check the date is not less than 30 days from the current date. So i am having a condition as below:

date.CompareTo(new DateTime().AddDays(-30)) < 0

but doesn't working. cant we add a negative number to date? if not how to achieve this?

Upvotes: 1

Views: 282

Answers (6)

Simon Brydon
Simon Brydon

Reputation: 985

You could do:

date < DateTime.Now.AddDays(-30);

This includes time as well. If you don't want that, try:

date < DateTime.Today.AddDays(-30);

Upvotes: 0

Habib
Habib

Reputation: 223207

Instead of new DateTime() you need DateTime.Now for current date

so your check should be:

date.CompareTo(DateTime.Now.AddDays(-30)) < 0

You can also do:

if(date < DateTime.Now.AddDays(-30))

EDIT: (from comment of @Rawling)

If you want to compare against the Date part of the DateTime, then you may use DateTime.Now.Date or DateTime.Today instead of DateTime.Now which will point to current date with 12:00AM time

date.Compare(DateTime.Now.Date.AddDays(-30)) < 0

Upvotes: 4

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can try with

DateTime.Now.AddDays(-30);

Upvotes: 0

burning_LEGION
burning_LEGION

Reputation: 13450

date.CompareTo(DateTime.UtcNow.AddDays(-30)) < 0

Upvotes: 0

iJade
iJade

Reputation: 23791

Try this..

DateTime.Now.AddDays(No of Days)

Upvotes: 0

Danilo Vulović
Danilo Vulović

Reputation: 3063

date.CompareTo(DateTime.Now.AddDays(-30)) < 0

Upvotes: 0

Related Questions