How to get the total number of days in a year from the given date

后端 未结 5 1013
别跟我提以往
别跟我提以往 2021-01-05 00:24

I would like to get the total number of days in a year left from the given date .. Assume if a user gives 04-01-2011(MM-DD-YYYY) I would like to find the remain

相关标签:
5条回答
  • 2021-01-05 00:38

    Perhaps just:

    DateTime.IsLeapYear(DateTime.Now.Year) ? 366 : 365

    Sorry, read it as if you just wanted the number of days in current year...

    0 讨论(0)
  • 2021-01-05 00:39

    I think you should try TimeSpan like

     DateTime startTime = DateTime.Now;
    
     DateTime endTime = DateTime.Now.AddSeconds( 75 );
    
     TimeSpan span = endTime.Subtract ( startTime );
     Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
     Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
     Console.WriteLine( "Time Difference (hours): " + span.Hours );
     Console.WriteLine( "Time Difference (days): " + span.Days );
    
    0 讨论(0)
  • 2021-01-05 00:46

    should do the trick

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

    0 讨论(0)
  • 2021-01-05 00:50

    new DateTime(suppliedDate.Year, 12, 31).Subtract(suppliedDate).TotalDays

    0 讨论(0)
  • 2021-01-05 00:52

    Let's say the date is today:

    var user = "05-08-2012";
    var date = DateTime.ParseExact(user, "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);
    var lastdate = new DateTime(date.Year, 12, 31);
    var diff = lastdate - date;
    

    diff.TotalDays contains the number of days (thanks @Tung). lastdate also contains the last date for the year.

    0 讨论(0)
提交回复
热议问题