Michael Benson
Michael Benson

Reputation: 71

C# - How many days left in year from Datetime.Now

I'm trying to get the number of days left in a year from Datetime.Now.

Having a little trouble, I tried using a datediff without much success.

I don't suppose one of you experts could perhaps show me how this would be achieved in C#?

I'd like a code to return an integer value for the days remaining.

Upvotes: 4

Views: 5470

Answers (8)

Matěj Štágl
Matěj Štágl

Reputation: 1037

One liner, based on top voted answer:

DateTime.IsLeapYear(DateTime.Today.Year) ? 366 - DateTime.Today.DayOfYear : 365 - DateTime.Today.DayOfYear

Upvotes: 0

Ali Raza
Ali Raza

Reputation: 99

Assuming that you have bigger date (endDate) and you want to know how many days big ,

int days = endDate.Subtract(startDate).Days;

Upvotes: 0

Eddy
Eddy

Reputation: 5360

Already a lot of answers that work, but haven't seen this simple one yet

DateTime today = DateTime.Now;
int daysleft = new DateTime(today.Year,12,31).DayOfYear - today.DayOfYear;

Upvotes: -1

Tim Lloyd
Tim Lloyd

Reputation: 38434

DateTime now = DateTime.Now;
DateTime end = new DateTime(now.Year + 1, 1, 1);
int daysLeftInYear = (int)(end - now).TotalDays;

Upvotes: 5

Joe Doyle
Joe Doyle

Reputation: 6383

How about this:

    public int DaysLeftInYear()
    {
        DateTime today = DateTime.Now;
        int daysInYear = 365;
        if (DateTime.IsLeapYear(today.Year))
        {
            daysInYear++;
        }

        return daysInYear - today.DayOfYear;
    }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499750

How about:

DateTime date = DateTime.Today;
int daysInYear = DateTime.IsLeapYear(date.Year) ? 366 : 365;
int daysLeftInYear = daysInYear - date.DayOfYear; // Result is in range 0-365.

Note that it's important to only evaluate DateTime.Now once, otherwise you could get an inconsistency if it evaluates once at the end of one year and once at the start of another.

Upvotes: 8

Jason
Jason

Reputation: 89082

something like this...

DateTime EOY = new DateTime(DateTime.Now.Year, 12, 31);
int DaysLeft = EOY.Subtract(DateTime.Now).Days;

Upvotes: 0

Tridus
Tridus

Reputation: 5081

Off the top of my head, you could do this:

Date someDate = DateTime.Now;
Date nextYear = new DateTime(someDate.Year + 1, 1, 1);
int daysLeft = (nextYear - someDate).Days;

Not tested because I'm at home, but I'm pretty sure on the logic. :)

Upvotes: 2

Related Questions