Count the number of days per month between two dates
Something like this? You get the days per month even for leap years like february 2020.
function getDays() {
var dropdt = new Date(document.getElementById("arr").value);
var pickdt = new Date(document.getElementById("dep").value);
var result = "";
for (var year = dropdt.getFullYear(); year <= pickdt.getFullYear(); year++) {
var firstMonth = (year == dropdt.getFullYear()) ? dropdt.getMonth() : 0;
var lastMonth = (year == pickdt.getFullYear()) ? pickdt.getMonth() : 11;
for (var month = firstMonth; month <= lastMonth; month++) {
var firstDay = (year === dropdt.getFullYear() && month === firstMonth) ? dropdt.getDate() : 1;
var lastDay = (year === pickdt.getFullYear() && month === lastMonth) ? pickdt.getDate() : 0;
var lastDateMonth = (lastDay === 0) ? (month + 1) : month
var firstDate = new Date(year, month, firstDay);
var lastDate = new Date(year, lastDateMonth, lastDay);
result += (month + 1) + " - " + parseInt((lastDate - firstDate) / (24 * 3600 * 1000) + 1) + "; ";
}
}
return result;
}
function cal() {
if (document.getElementById("dep")) {
document.getElementById("number-of-dates").value = getDays();
}
}
<form action="javascript:void(0);">
<input id="arr" type="date" name="arr" value="2019-09-15">
<input id="dep" type="date" name="dep" value="2020-03-15">
<button onclick="cal()">Calculate</button>
<input style="width:400px" id="number-of-dates" type="text">
</form>
How to calculate number of days between two dates?
Here is a quick and dirty implementation of datediff
, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).
// new Date("dateString") is browser-dependent and discouraged, so we'll write
// a simple parse function for U.S. date format (which does no error checking)
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function datediff(first, second) {
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
return Math.round((second-first)/(1000*60*60*24));
}
alert(datediff(parseDate(first.value), parseDate(second.value)));
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
Calculating number of days between two dates
you do not need DateDif for just number of days. Just subtract the two numbers and format the output as general.
=IF(B2<>"",IF(C2<>"",C2-B2,today()-B2),"")
count the number of days between two dates per year
Here's one approach using tidyverse
and lubridate
.
First, separate the rows by calendar year, to use to measure the number of days for each year. Each row will include dates to be counted in each calendar year, starting with January 1st and ending with December 31st if overlapping multiple years. Then, it is easy to calculate the number of days in a given year.
The results from this example are slightly different than what I have. Year 2016 is a leap year and has 366 days. If the number of days are not inclusive of either start or end dates, you would get a different answer.
library(tidyverse)
library(lubridate)
df %>%
mutate(date_int = interval(start, end),
year = map2(year(start), year(end), seq)) %>%
unnest(year) %>%
mutate(year_int = interval(as.Date(paste0(year, '-01-01')), as.Date(paste0(year, '-12-31'))),
year_sect = intersect(date_int, year_int),
start_new = as.Date(int_start(year_sect)),
end_new = as.Date(int_end(year_sect))) %>%
select(id, start_new, end_new) %>%
mutate(year = year(start_new),
days = as.numeric(end_new - start_new)) %>%
right_join(df) %>%
pivot_wider(id_cols = c(id, start, end), names_from = year, values_from = days, names_prefix = "year_", values_fill = list(days = 0)) %>%
mutate(days_number = reduce(select(., starts_with("year_")), `+`))
Output
id start end year_2015 year_2016 days_number
<dbl> <date> <date> <dbl> <dbl> <dbl>
1 1 2015-01-01 2016-12-31 364 365 729
2 2 2016-01-01 2016-12-31 0 365 365
3 3 2015-07-01 2016-12-31 183 365 548
Excel - count days between two dates per year
Put this in C2 and copy over:
=MIN(DATE(C1,12,31),$B$2)-MAX(DATE(C1,1,1),$A$2)
Get calendar days between two dates
You don't need string manipulation to get a DateTime without the time part, just use DateTime.Date.
To get the time span between two dates, just subtract one from the other. Subtracting one date from another returns a TimeSpan object whose Days property is the difference in full dates.
All you need to do is :
Dim days As Integer =(date2.Date-date1.Date).Days
This way you avoid generating and parsing temporary strings.
Calculate number of days between two dates?
Your program seems to work as intended. I'm getting 45.55 hours. Have you tried to run it locally?
Playground time is fixed, time.Now() will give you 2009-11-10 23:00:00 +0000 UTC always.
Related Topics
How to Return Something Early from a Block
How to Use Unicorn as "Rails S"
Test Whether a Variable Equals Either One of Two Values
How to Set the Default String Encoding on Ruby 1.9
Rails Erb Form Helper Options_For_Select :Selected
How to Add MAC-Specific Gems to Bundle on MAC But Not on Linux
Nokogiri: Select Content Between Element a and B
Does Ruby Have the Java Equivalent of Synchronize Keyword
Error When Doing Rake Db:Migrate on Heroku
Cannot Execute "Rails Console" Due to an Error with Readline
Execute a Rake Task from Within Migration
How to Convert PDF Files to Images Using Rmagick and Ruby
Ruby - Determining Method Origins