Finding the Number of Days Between Two Dates

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"/>

How to find the difference in days between two dates?

If you have GNU date, it allows to print the representation of an arbitrary date (-d option).
In this case convert the dates to seconds since EPOCH, subtract and divide by 24*3600.

Example using GNU date (from https://stackoverflow.com/a/9008871/215713):

let DIFF=($(date +%s -d 20210131)-$(date +%s -d 20210101))/86400
echo $DIFF
30

This also works with dates in other formats, for example "2021-01-31".

Other answers suggest ways to do it that don't require GNU date.

How to calculate number of days between two dates

http://momentjs.com/ or https://date-fns.org/

From Moment docs:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1

or to include the start:

a.diff(b, 'days')+1   // =2

Beats messing with timestamps and time zones manually.

Depending on your specific use case, you can either

  1. Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments).
  2. Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
  3. Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.

Finding the number of days between two dates

$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;

echo round($datediff / (60 * 60 * 24));

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

How to calculate the number of days between two dates?

const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);

const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));

Flutter: Find the number of days between two dates

You can use the difference method provide by DateTime class

 //the birthday's date
final birthday = DateTime(1967, 10, 12);
final date2 = DateTime.now();
final difference = date2.difference(birthday).inDays;

UPDATE

Since many of you reported there is a bug with this solution and to avoid more mistakes, I'll add here the correct solution made by @MarcG, all the credits to him.

  int daysBetween(DateTime from, DateTime to) {
from = DateTime(from.year, from.month, from.day);
to = DateTime(to.year, to.month, to.day);
return (to.difference(from).inHours / 24).round();
}

//the birthday's date
final birthday = DateTime(1967, 10, 12);
final date2 = DateTime.now();
final difference = daysBetween(birthday, date2);

This is the original answer with full explanation: https://stackoverflow.com/a/67679455/666221

Informix SQL - Number of days between 2 dates

What version of Informix are you using?

Here is an example using Informix 14.10.FC5 :

CREATE TABLE mytable
(
id INTEGER,
date1 DATETIME YEAR TO SECOND,
date2 DATETIME YEAR TO SECOND
);
-- Using 2021-02-28 instead of 2021-02-29 because 2021-02-29 is an incorrect date and Informix returns an error.
INSERT INTO mytable VALUES ( 1, '2021-02-28 00:00:00', '2021-09-27 00:00:00' );
INSERT INTO mytable VALUES ( 2, '1900-12-31 00:00:00', '2021-09-27 00:00:00' );

SELECT
date1,
date2,
( date1 - date2 )::INTERVAL DAY(9) TO DAY AS daysdifference1, -- no need to transform the datetime with "extend". I just cast the result to an interval of days
( date2 - date1 )::INTERVAL DAY(9) TO DAY AS daysdifference2
FROM
mytable
WHERE
id = 1
;

date1 date2 daysdifference1 daysdifference2

2021-02-28 00:00:00 2021-09-27 00:00:00 -211 211

SELECT
date1,
date2,
( date1 - date2 )::INTERVAL DAY(9) TO DAY AS daysdifference1, -- no need to transform the datetime with "extend". I just cast the result to an interval of days
( date2 - date1 )::INTERVAL DAY(9) TO DAY AS daysdifference2
FROM
mytable
WHERE
id = 2
;

date1 date2 daysdifference1 daysdifference2

1900-12-31 00:00:00 2021-09-27 00:00:00 -44100 44100


Related Topics



Leave a reply



Submit