Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate how many days passed from today's date

Here is my issue:

I'm trying to calculate how many days passed from today's date and display it in a label.The issue is when the user changing the time,the result that I'm getting back is in fractions.

Please assist

Here is my code in JS:

 //=============================================== //
   // How many days passed from the current day     //
   // ============================================ //

   function BanDateChanged(sender, args) {
       var banDate = $find("<%= rdtpBan.ClientID %>");
       var TodayDate = new Date();
       var today = new Date();
       var todayFormat = new Date(today.getMonth() + 1 + "/" + today.getDate() + "/" + today.getFullYear());
       var banSelectedDate = banDate.get_selectedDate();
       var countedBannedDays = document.getElementById("<%= lblBanCountDays.ClientID %>");
       var one_day = 1000 * 60 * 60 * 24;
       var countedDays = (Math.ceil(todayFormat - banSelectedDate) / one_day);
       if (countedDays == 0) {
           countedBannedDays.innerHTML = "";
       } else {
           countedBannedDays.innerHTML = countedDays + " Days ago";
       }
   }
like image 870
Huy Zukerman Avatar asked Jun 17 '15 23:06

Huy Zukerman


People also ask

How to calculate how many days are left to the date?

To calculate how many days left to the date: = DATEDIF (TODAY (), <end date>, “d”) Note: You can use a simpler formula that yields the same result: = <end date> - TODAY ().

How do I use the calculator to calculate the date?

The calculator checks the date from all days or from weekdays from today. For example, what date will be 30, 45, 60 or 90 days from today. To use the calculator, just enter the number of days in one of the fields. Remember that the calculator does not include holidays in the calculations.

How does our days calculator work?

Our Days Calculator easily counts it within seconds. Whether the date may be from the past or future. It doesn't matter. It just takes two inputs from the user side. Start date and End date. That's it. Also, it gives you output in years, months, days, hours, and even seconds.

How do I Count the days between today and today?

Excel Formula: Count Days from Today. ... To count the days between today and the specific date in cell B3, please use below formula: =ABS(IF(ISBLANK(B3),"",TODAY()-B3)) Press Enter key to get the result. Then drag auto fill handle over other cells to apply this formula as you need.


Video Answer


3 Answers

General case

This and many similar tasks were traditionally solved by reinventing the same solution over and over again, leading to problems during the development like you experienced here, and leaving a maintainability nightmare for the future.

Fortunately there is a small library available for exactly cases like this: Moment.js.

Counting days

To display how many days have passed since a given date:

var days = moment().diff("2015-06-02", "days");

It handles rounding for you, it handles daylight saving boundaries, it handles time zones, it handles date format parsing for you etc. - there is really no need to reinvent the wheel and write the same code many, many times. See: DEMO.

But it gets even better than that:

More intelligent output

You can use this instead:

var ago = moment.duration(moment().diff("2015-06-05")).humanize() + " ago";

and you will automatically get values like:

  • "15 days ago"
  • "13 hours ago"
  • "5 years ago"

that would be ready to put in your countedBannedDays.innerHTML giving your users more informative values. See: DEMO.

Your example

In your example, as long as the value of your banSelectedDate contains a valid date, then your code - with the DOM handling code removed because that would stay the same:

    var banDate = $find("<%= rdtpBan.ClientID %>");
    var TodayDate = new Date();
    var today = new Date();
    var todayFormat = new Date(today.getMonth() + 1 + "/" + today.getDate() + "/" + today.getFullYear());
    var banSelectedDate = banDate.get_selectedDate();
    var one_day = 1000 * 60 * 60 * 24;
    var countedDays = (Math.ceil(todayFormat - banSelectedDate) / one_day);

can be simplified to just:

    var banDate = $find("<%= rdtpBan.ClientID %>");
    var banSelectedDate = banDate.get_selectedDate();
    var countedDays = moment().diff(banSelectedDate, "days");

with the relevant days counting logic being just:

var countedDays = moment().diff(banSelectedDate, "days");

It's obvious what's going on, you don't have to handle weird edge cases, you avoid exposing internal data representations leading to leaky abstractions, and there is really not much room to make any mistake.

Other options

There are also other libraries:

  • XDate
  • DateJS

See more info in this answer.

With good libraries available to handle such common tasks we don't have to write complicated code with many potential problems like the ones you had here. Code reuse not only allows you to avoid potential problems but it makes your own code much more maintainable.

like image 57
rsp Avatar answered Sep 23 '22 11:09

rsp


Javascript dates are really just a timevalue that is milliseconds since 1970-01-01T00:00:00Z. To get the number of milliseconds between two dates, just subtract one from the other:

var date0 = new Date(2015, 0, 1); // 1 Jan 2015
var date1 = new Date(2015, 1, 1); // 1 Feb 2015

var numberOfDays = Math.ceil((date1 - date0) / 8.64e7); // 31

Do not use the Date constructor to parse strings. If you know the values, pass them directly (remembering that months are zero indexed).

To find out how many days have a passed since the beginning of the month, just use the day number:

var now = new Date();
var daysSinceStartOfMonth = now.getDate() - 1;

so on the 1st it will return 0, on the 2nd it will return 1 and so on. If you want to do it your way (which works but is a lot more work than it needs to be), then:

// Create a date object for the current instant
var now = new Date();

// Make an exact copy
var startOfMonth = new Date(+now);

// Set the copy's date to the start of the month
startOfMonth.setDate(1);

// Get the difference in time value and calculate whole days
var daysSinceStartOfMonth = Math.ceil((now - startOfMonth) / 8.64e7); // 17 on 18 June

The only need for Math.ceil is if the dates cross a daylight saving boundary. Hope that helps.

like image 23
RobG Avatar answered Sep 19 '22 11:09

RobG


You can get fractional results because of the mismatch in the time information so what you are looking for are "whole" days for a nice, round result. You can do that in a couple of ways. One is you can clear the time information from the dates being used by using the setHours() etc. functions. The second way would be to create a new Date object from banSelectedDate but without using its time information, like so:

var cDate = new Date(banSelectedDate.getFullYear(), banSelectedDate.getMonth(), banSelectedDate.getDate());

Then use cDate for the calculation.

like image 32
Satyajit Avatar answered Sep 22 '22 11:09

Satyajit