Days between dates: Difference between revisions

no edit summary
No edit summary
(16 intermediate revisions by 10 users not shown)
Line 12:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F parse_date(date)
R time:strptime(date, ‘%Y-%m-%d’)
 
V date1 = parse_date(‘2019-01-01’)
V date2 = parse_date(‘2019-09-30’)
print((date2 - date1).days())</langsyntaxhighlight>
 
{{out}}
Line 26:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
TYPE Date=[CARD year BYTE month,day]
Line 109:
Test("2090-01-01","2098-12-25")
Test("1902-01-01","2098-12-25")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Days_between_dates.png Screenshot from Atari 8-bit computer]
Line 124:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Calendar;
with Ada.Text_IO;
with Ada.Integer_Text_IO;
Line 168:
Put_Days_Between ("2090-01-01", "2098-12-25", "Future");
Put_Days_Between ("1902-01-01", "2098-12-25", "Long span");
end Days_Between_Dates;</langsyntaxhighlight>
 
{{out}}
Line 179:
Days between 2090-01-01 and 2098-12-25 is 3280 days -- Future
Days between 1902-01-01 and 2098-12-25 is 71947 days -- Long span</pre>
 
=={{header|ALGOL 68}}==
{{Trans|FreeBASIC}}
<syntaxhighlight lang="algol68">
BEGIN # calculate the number of days between a pair of dates #
# based on a translation of the FreeBASIC sample #
 
[,]STRING test cases
= ( ( "1902-01-01", "1968-12-25" )
, ( "2019-01-01", "2019-01-02" ), ( "2019-01-02", "2019-01-01" )
, ( "2019-01-01", "2019-03-01" ), ( "2020-01-01", "2020-03-01" )
, ( "1995-11-21", "1995-11-21" ), ( "2090-01-01", "2098-12-25" )
);
 
PROC gregorian = ( INT y, m, d )INT:
BEGIN
INT n = ( m + 9 ) - ( ( ( m + 9 ) OVER 12 ) * 12 );
INT w = y - ( n OVER 10 );
( 365 * w ) + ( w OVER 4 ) - ( w OVER 100 ) + ( w OVER 400 )
+ ( ( ( n * 306 ) + 5 ) OVER 10 ) + ( d - 1 )
END # gregorian # ;
 
OP TOINT = ( STRING s )INT:
BEGIN
INT v := 0;
FOR s pos FROM LWB s TO UPB s DO
v *:= 10 +:= ( ABS s[ s pos ] - ABS "0" )
OD;
v
END # TOINT #;
 
FOR n FROM LWB test cases TO UPB test cases DO
STRING from date = test cases[ n, 1 ];
STRING to date = test cases[ n, 2 ];
INT from g = gregorian( TOINT from date[ 1 : 4 ]
, TOINT from date[ 6 : 7 ]
, TOINT from date[ 9 : 10 ]
);
INT to g = gregorian( TOINT to date[ 1 : 4 ]
, TOINT to date[ 6 : 7 ]
, TOINT to date[ 9 : 10 ]
);
print( ( "Days between ", from date, " and ", to date, " is " ) );
print( ( whole( to g - from g, -5 ), " days", newline ) )
OD
END
</syntaxhighlight>
{{out}}
<pre>
Days between 1902-01-01 and 1968-12-25 is 24465 days
Days between 2019-01-01 and 2019-01-02 is 1 days
Days between 2019-01-02 and 2019-01-01 is -1 days
Days between 2019-01-01 and 2019-03-01 is 59 days
Days between 2020-01-01 and 2020-03-01 is 60 days
Days between 1995-11-21 and 1995-11-21 is 0 days
Days between 2090-01-01 and 2098-12-25 is 3280 days
</pre>
 
=={{header|ALGOL W}}==
{{Trans|FreeBASIC}}
<syntaxhighlight lang="algolw">
begin % calculate the number of days between a pair of dates %
% based on a translation of the FreeBASIC sample %
 
integer procedure gregorian ( integer value y, m, d ) ;
begin
integer n, w;
n := ( m + 9 ) - ( ( ( m + 9 ) div 12 ) * 12 );
w := y - ( n div 10 );
( 365 * w ) + ( w div 4 ) - ( w div 100 ) + ( w div 400 )
+ ( ( ( n * 306 ) + 5 ) div 10 ) + ( d - 1 )
end gregorian ;
 
integer procedure toInt( string(4) value s ) ;
begin
integer v;
v := 0;
for sPos := 0 until 3 do begin
string(1) c;
c := s( sPos // 1 );
if c not = " " then v := ( v * 10 ) + ( decode( c ) - decode( "0" ) )
end;
v
end toInt ;
 
procedure testGregorian ( string(10) value fromDate, toDate ) ;
begin
integer fromG, toG;
fromG := gregorian( toInt( fromDate( 0 // 4 ) )
, toInt( fromDate( 5 // 2 ) )
, toInt( fromDate( 8 // 2 ) )
);
toG := gregorian( toInt( toDate( 0 // 4 ) )
, toInt( toDate( 5 // 2 ) )
, toInt( toDate( 8 // 2 ) )
);
writeon( s_w := 0, "Days between ", fromDate, " and ", toDate, " is " );
writeon( i_w := 5, s_w := 0, toG - fromG, " days" );
write();
end testGregorian ;
 
testGregorian( "1902-01-01", "1968-12-25" );testGregorian( "2019-01-01", "2019-01-02" );
testGregorian( "2019-01-02", "2019-01-01" );testGregorian( "2019-01-01", "2019-03-01" );
testGregorian( "2020-01-01", "2020-03-01" );testGregorian( "1995-11-21", "1995-11-21" );
testGregorian( "2090-01-01", "2098-12-25" )
 
end.
</syntaxhighlight>
{{out}}
<pre>
Days between 1902-01-01 and 1968-12-25 is 24465 days
Days between 2019-01-01 and 2019-01-02 is 1 days
Days between 2019-01-02 and 2019-01-01 is -1 days
Days between 2019-01-01 and 2019-03-01 is 59 days
Days between 2020-01-01 and 2020-03-01 is 60 days
Days between 1995-11-21 and 1995-11-21 is 0 days
Days between 2090-01-01 and 2098-12-25 is 3280 days
</pre>
 
=={{header|AppleScript}}==
 
<langsyntaxhighlight lang="applescript">on daysBetweenDates(date1, date2)
considering numeric strings -- Allows for leading zeros having been omitted.
if (date1 = date2) then return date1 & " and " & date2 & " are the same date"
Line 219 ⟶ 337:
return daysBetweenDates("2020-04-11", "2001-01-01") & linefeed & ¬
daysBetweenDates("2020-04-11", "2020-04-12") & linefeed & ¬
daysBetweenDates("2020-04-11", "2020-04-11")</langsyntaxhighlight>
 
{{output}}
Line 229 ⟶ 347:
Or, composing a function from reusable generics, and drawing on NSISO8601DateFormatter:
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 360 ⟶ 478:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>2020-04-11 -> 2001-01-01 -> -7040 days
Line 371 ⟶ 489:
{{trans|Ruby}}
 
<langsyntaxhighlight lang="rebol">daysBetweenDates: function [startDate, endDate][
a: to :date.format: "dd/MM/yyyy" startDate
b: to :date.format: "dd/MM/yyyy" endDate
Line 381 ⟶ 499:
"days between the two dates:"
daysBetweenDates "01/01/2019" "19/10/2019"
]</langsyntaxhighlight>
 
{{out}}
Line 388 ⟶ 506:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">db =
<lang AutoHotkey>db =
(
1995-11-21|1995-11-21
Line 412 ⟶ 530:
EnvSub, D2, % D1, days
return D2
}</langsyntaxhighlight>
{{out}}
<pre>Days between 1995-11-21 and 1995-11-21 : 0 Day(s)
Line 424 ⟶ 542:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DAYS_BETWEEN_DATES.AWK
BEGIN {
Line 466 ⟶ 584:
return(result)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 499 ⟶ 617:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include<stdbool.h>
#include<string.h>
Line 559 ⟶ 677:
return 0;
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 570 ⟶ 688:
The <code>date</code> namespace is taken from bqn-libs. <code>DBw</code> is the final function which calculates the proper difference between two date strings.
 
<langsyntaxhighlight lang="bqn">DivMod ← ⌊∘÷˜ ⋈ |
date ← {
o ← 719469
Line 593 ⟶ 711:
 
S2D←ToI¨ '-'⊸Split
DBw ← -○(date.From S2D)</langsyntaxhighlight>
<pre> "2019-09-30" DBw "2019-01-01"
272</pre>
Line 600 ⟶ 718:
=={{header|C++}}==
{{trans|c}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
 
Line 736 ⟶ 854:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Days difference : 335</pre>
Line 742 ⟶ 860:
===Alternative using Boost===
{{libheader|Boost}}
<langsyntaxhighlight lang="cpp">#include <cstdlib>
#include <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>
Line 761 ⟶ 879:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 770 ⟶ 888:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Globalization;
 
Line 782 ⟶ 900:
return (int)(b - a).TotalDays;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 791 ⟶ 909:
{{works with|GnuCOBOL}}
 
<langsyntaxhighlight COBOLlang="cobol">COBOL *> days-between
*> Tectonics: cobc -xj days-between.cob
 
Line 811 ⟶ 929:
 
goback.
end program days-between.</langsyntaxhighlight>
 
{{out}}
Line 820 ⟶ 938:
 
=={{header|Commodore BASIC}}==
<syntaxhighlight lang="gwbasic">
<lang GWBasic>
100 REM ===============================
110 REM DAYS BETWEEN 2 DATES
Line 872 ⟶ 990:
9080 G=G+INT((N*306+5)/10)+(D-1)
9090 RETURN
</syntaxhighlight>
</lang>
 
 
Line 879 ⟶ 997:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.datetime.date;
import std.stdio;
 
Line 887 ⟶ 1,005:
auto diff = toDate - fromDate;
writeln("Number of days between ", fromDate, " and ", toDate, ": ", diff.total!"days");
}</langsyntaxhighlight>
{{out}}
<pre>Number of days between 2019-Jan-01 and 2019-Oct-07: 279</pre>
Line 893 ⟶ 1,011:
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Days_between_dates;
 
Line 925 ⟶ 1,043:
Writeln(DaysBetween('1970-01-01', '2019-10-18'));
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>18187</pre>
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
 
-module(daysbetween).
Line 952 ⟶ 1,070:
 
</langsyntaxhighlight>
{{out}}
erlang shell:
Line 1,066 ⟶ 1,184:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Days between dates: Nigel Galloway. June 3rd., 2021
let n,g=System.DateTime.Parse("1792-9-22"),System.DateTime.Parse("1805-12-31")
printfn "There are %d days between %d-%d-%d and %d-%d-%d" (g-n).Days n.Year n.Month n.Day g.Year g.Month g.Day
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,077 ⟶ 1,195:
=={{header|Factor}}==
Factor supports the addition and subtraction of timestamps and durations with the <code>time+</code> and <code>time-</code> words.
<langsyntaxhighlight lang="factor">USING: calendar calendar.parser kernel math prettyprint ;
 
: days-between ( ymd-str ymd-str -- n )
Line 1,083 ⟶ 1,201:
 
"2019-01-01" "2019-09-30" days-between .
"2016-01-01" "2016-09-30" days-between . ! leap year</langsyntaxhighlight>
{{out}}
<pre>
Line 1,092 ⟶ 1,210:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">Dim Shared As Integer M, Y, D
Dim As Integer Y1, M1, D1, Y2, M2, D2, G1, G2
Dim As String DaysBetween(7, 2) = {{"1902-01-01","1968-12-25"}, _
Line 1,119 ⟶ 1,237:
Print Using "##### days"; (G2-G1)
Next n
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 1,130 ⟶ 1,248:
Days between 2090-01-01 and 2098-12-25 is 3280 days
</pre>
 
 
=={{header|Frink}}==
Line 1,139 ⟶ 1,256:
See Frink's [https://frinklang.org/#DateTimeHandling Date/Time Handling] documentation to see how easy it is to work with dates, times, timezones, calendrical systems, and even leap seconds correctly and easily.
 
<langsyntaxhighlight lang="frink">d1 = # 2020-12-25 #
d2 = # 2020-12-06 #
println[d1-d2 -> days]</langsyntaxhighlight>
 
{{out}}
Line 1,149 ⟶ 1,266:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?timeZone=America%2FLos_Angeles&script=examples/Days_between_dates}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
Note. For this script, the time zone is intentionally set to America/Los_Angeles, because it observes [https://en.wikipedia.org/wiki/Daylight_saving_time daylight saving time], It is necesary to solve this exercise.
In '''[https://formulae.org/?timeZone=America%2FLos_Angeles&example=Days_between_dates this]''' page you can see the program(s) related to this task and their results.
 
Provided that the ToNumber expression applied to a time expression reduces to the number of milliseconds of such that time from the [https://en.wikipedia.org/wiki/Epoch_(computing) epoch]:
 
[[File:Fōrmulæ - Days between dates 01.png]]
 
[[File:Fōrmulæ - Days between dates 02.png]]
 
The solution seems easy, calculating the difference between two times (in milliseconds), and dividing by 86,4000,000 (number of milliseconds in a day):
 
[[File:Fōrmulæ - Days between dates 03.png]]
 
[[File:Fōrmulæ - Days between dates 04.png]]
 
However, it does not work if one time is in daylight saving time, and the other one is in standard time:
 
[[File:Fōrmulæ - Days between dates 05.png]]
 
[[File:Fōrmulæ - Days between dates 06.png]]
 
[[File:Fōrmulæ - Days between dates 07.png]]
 
[[File:Fōrmulæ - Days between dates 08.png]]
 
'''Solution 1'''
 
The first solution consists in simply rounding the result to the nearest integer:
 
[[File:Fōrmulæ - Days between dates 09.png]]
 
[[File:Fōrmulæ - Days between dates 10.png]]
 
'''Solution 2'''
 
The expression GetTimeZoneOffset reduces to the offset (in minutes) of the given time.
 
[[File:Fōrmulæ - Days between dates 11.png]]
 
[[File:Fōrmulæ - Days between dates 12.png]]
 
[[File:Fōrmulæ - Days between dates 13.png]]
 
[[File:Fōrmulæ - Days between dates 14.png]]
 
The solution consist in taking this difference in account.
 
So, the function that works correctly is:
 
[[File:Fōrmulæ - Days between dates 15.png]]
 
'''Test cases'''
 
[[File:Fōrmulæ - Days between dates 16.png]]
 
[[File:Fōrmulæ - Days between dates 17.png]]
 
Notice that it works even for fractions of days:
 
[[File:Fōrmulæ - Days between dates 18.png]]
 
[[File:Fōrmulæ - Days between dates 19.png]]
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,193 ⟶ 1,370:
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}</langsyntaxhighlight>
 
{{out}}
Line 1,203 ⟶ 1,380:
=={{header|Groovy}}==
{{trans|Kotlin}} {{trans|Java}}
<langsyntaxhighlight lang="groovy">import java.time.LocalDate
 
def fromDate = LocalDate.parse("2019-01-01")
def toDate = LocalDate.parse("2019-10-19")
def diff = fromDate - toDate
println "Number of days between ${fromDate} and ${toDate}: ${diff}"</langsyntaxhighlight>
{{out}}
<pre>Number of days between 2019-01-01 and 2019-10-19: 291</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.Time (Day)
import Data.Time.Calendar (diffDays)
import Data.Time.Format (parseTimeM,defaultTimeLocale)
Line 1,232 ⟶ 1,409:
 
stringToDay :: String -> Maybe Day
stringToDay date = parseTimeM True defaultTimeLocale "%Y-%-m-%-d" date</langsyntaxhighlight>
{{out}}
<pre>There are 272 days between 2019-01-01 and 2019-09-30.
Line 1,239 ⟶ 1,416:
Or, composing rather than raising errors:
 
<langsyntaxhighlight lang="haskell">import Data.Time (Day)
import Data.Time.Calendar (diffDays)
import Data.Time.Format (defaultTimeLocale, parseTimeM)
Line 1,281 ⟶ 1,458:
]
)
$ daysBetween s1 s2</langsyntaxhighlight>
{{Out}}
<pre>There are 272 days between 2019-01-01 and 2019-09-30.
Line 1,304 ⟶ 1,481:
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="java">import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
 
Line 1,314 ⟶ 1,491:
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}</langsyntaxhighlight>
{{out}}
<pre>Number of days between 2019-01-01 and 2019-10-19: 291</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">const timeRatio = 1000 * 60 * 60 * 24;
var floor = Math.floor, abs = Math.abs;
var daysBetween = (d1, d2) => floor(abs(new Date(d1) - new Date(d2)) / timeRatio);
 
console.log('Days between 2021-10-27 and 2020-03-03: %s', daysBetween('2021-10-27', '2020-03-03'));</langsyntaxhighlight>
{{out}}
<pre>Days between 2021-10-27 and 2020-03-03: 603</pre>
Line 1,337 ⟶ 1,514:
 
===Using jq's built-ins===
<syntaxhighlight lang="jq">
<lang jq>
def days_between(yyyymmddBefore; yyyymmddAfter):
(yyyymmddBefore | strptime("%Y-%m-%d") | mktime) as $before
Line 1,367 ⟶ 1,544:
 
task
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,389 ⟶ 1,566:
===From first principles===
'''Adapted from [[#Wren|Wren]]'''
<syntaxhighlight lang="jq">
<lang jq>
# In general, dates should be valid Julian dates on or after Jan 1, 0001, but
# for the most part, this is not checked, in part because some
Line 1,432 ⟶ 1,609:
| (date | toa) as $date
| days_between($date[0]; $date[1]; $date[2]; $later[0]; $later[1]; $later[2]);
</syntaxhighlight>
</lang>
'''The Tasks'''
 
Line 1,441 ⟶ 1,618:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Dates
 
@show Day(DateTime("2019-09-30") - DateTime("2019-01-01"))
Line 1,450 ⟶ 1,627:
@show Day(DateTime("2029-03-29") - DateTime("2019-03-29"))
</langsyntaxhighlight>{{out}}
<pre>
Day(DateTime("2019-09-30") - DateTime("2019-01-01")) = 272 days
Line 1,459 ⟶ 1,636:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">import java.time.LocalDate
import java.time.temporal.ChronoUnit
 
Line 1,467 ⟶ 1,644:
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}</langsyntaxhighlight>
{{out}}
<pre>Number of days between 2019-01-01 and 2019-10-19: 291</pre>
Line 1,473 ⟶ 1,650:
=={{header|Lua}}==
This uses os.difftime to compare two Epoch times. Not to be used with dates before 1970.
<langsyntaxhighlight lang="lua">SECONDS_IN_A_DAY = 60 * 60 * 24
 
-- Convert date string as YYYY-MM-DD to Epoch time.
Line 1,487 ⟶ 1,664:
local d2 = parseDate(io.read())
local diff = math.ceil(os.difftime(d2, d1) / SECONDS_IN_A_DAY)
print("There are " .. diff .. " days between these dates.")</langsyntaxhighlight>
{{out}}
<pre>Enter date 1: 1970-01-01
Enter date 2: 2019-10-02
There are 18171 days between these dates.</pre>
 
=={{header|M2000 Interpreter}}==
Version 12 has date type, so we can handle easy dates.
 
<syntaxhighlight lang="m2000 interpreter">
module Days_between_dates{
date a="2019-01-01", b="2019-09-30"
long z=b-a
// Use the system default to display dates (DD/MM/YYYY)
Print "Days from "+a+" to "+b+" = "+z
// using locale 1033 to display dates (MM/DD/YYYY)
Print "Days from "+date$(a, 1033)+" to "+date$(b, 1033)+" = "+z
}
Days_between_dates
</syntaxhighlight>
{{out}}
<pre>
Days from 1/1/2019 to 30/9/2019 = 272
Days from 1/1/2019 to 9/30/2019 = 272
</pre>
 
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">DateDifference["2020-01-01", "2020-03-01"]
DateDifference["2021-01-01", "2021-03-01"]</langsyntaxhighlight>
{{out}}
<pre>Quantity[60, "Days"]
Line 1,501 ⟶ 1,699:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import times
 
proc daysBetween(date1, date2: string): int64 =
Line 1,516 ⟶ 1,714:
 
for (date1, date2) in Dates:
echo "Days between ", date1, " and ", date2, ": ", daysBetween(date1, date2)</langsyntaxhighlight>
 
{{out}}
Line 1,526 ⟶ 1,724:
Days between 1902-01-01 and 1968-12-25: 24465
Days between 2090-01-01 and 2098-12-25: 3280</pre>
 
=={{header|Pascal}}==
==={{header|Free Pascal}}===
<syntaxhighlight lang="pascal">
Program DaysBetweenDates;
{$mode ObjFPC}{$H+}
 
Uses dateutils,strutils;
 
Type Tarr = array of array Of string;
 
Const lst : Tarr = (('1902-01-01','1968-12-25'),('2019-01-01','2019-01-02'),
('2019-01-02','2019-01-01'),('2019-01-01','2019-03-01'),
('2020-01-01','2020-03-01'),('1995-11-21','1995-11-21'),
('2090-01-01','2098-12-25'),('1967-02-23','2024-03-21'));
 
Function strtodate(str : String) : tdatetime;
Begin
result := ScanDateTime('YYYYMMDD', DelChars(str, '-'));
End;
 
Var arr : array of string;
DaysBetw : integer;
Begin
For arr In lst Do
Begin
DaysBetw := DaysBetween(strtodate(arr[0]),strtodate(arr[1]));
writeln(arr[0],' - ',arr[1],' -> ',DaysBetw);
End;
End.
</syntaxhighlight>
{{out}}
<pre>
1902-01-01 - 1968-12-25 -> 24465
2019-01-01 - 2019-01-02 -> 1
2019-01-02 - 2019-01-01 -> 1
2019-01-01 - 2019-03-01 -> 59
2020-01-01 - 2020-03-01 -> 60
1995-11-21 - 1995-11-21 -> 0
2090-01-01 - 2098-12-25 -> 3280
1967-02-23 - 2024-03-21 -> 20846
</pre>
 
=={{header|Perl}}==
Would not reinvent this wheel.
<langsyntaxhighlight lang="perl">use feature 'say';
use Date::Calc qw(Delta_Days);
 
Line 1,536 ⟶ 1,776:
say Delta_Days(2000,1,1, 2100,1,1); # another, with one extra leap day
say Delta_Days(2020,1,1, 2019,10,1); # backwards in time
say Delta_Days(2019,2,29, 2019,3,1); # croaks</langsyntaxhighlight>
{{out}}
<pre>427
Line 1,546 ⟶ 1,786:
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins<span style="color: #0000FF;">\<span style="color: #004080;">timedate<span style="color: #0000FF;">.<span style="color: #000000;">e</span>
<span style="color: #000080;font-style:italic;">-- specify as many or as few permitted formats as you like:</span>
Line 1,568 ⟶ 1,808:
<span style="color: #000000;">test<span style="color: #0000FF;">(<span style="color: #008000;">"1970-01-01"<span style="color: #0000FF;">,</span> <span style="color: #008000;">"2019/10/18"<span style="color: #0000FF;">)</span>
<span style="color: #000000;">test<span style="color: #0000FF;">(<span style="color: #008000;">"1970-01-01"<span style="color: #0000FF;">,</span> <span style="color: #008000;">"18/10/2019"<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
As shown, timedate_diff() can optionally round to the nearest whole number of days [else omit DT_DAY].<br>
Note that elapsed() assumes all years are exactly 365 days, and in no way takes leap years into consideration
Line 1,585 ⟶ 1,825:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de diffDates (A B)
(abs (- ($dat A "-") ($dat B "-"))) )
(println (diffDates "2019-1-1" "2019-9-30"))
(println (diffDates "2015-12-31" "2016-09-30"))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,595 ⟶ 1,835:
</pre>
 
=={{header|PL/I-80}}==
{{Trans|S-BASIC}}
<syntaxhighlight lang = "PL/I">
elapsed_days: proc options (main);
dcl
(date1, date2) float bin,
another char(1);
put skip list ('Elapsed days calculator');
another = 'Y';
do while ((another = 'Y') | (another = 'y'));
put skip list ('First date as YYYY-MM-DD : ');
date1 = get_date();
put list ('Second date as YYYY-MM-DD : ');
date2 = get_date();
put skip edit ('Elapsed days = ', date2-date1) (a,f(6));
put skip list ('Do another (y/n)? ');
get edit (another) (a);
end;
 
/*
* Read a date in YYYY-MM-DD format from the
* console and return its serial date equivalent
*/
get_date: proc returns (float bin);
dcl date char(20) varying;
dcl (y, m, d) float bin;
get edit (date) (a);
y = binary(substr(date,1,4));
m = binary(substr(date,6,2));
d = binary(substr(date,9,2));
return (serial_date(y,m,d));
end get_date;
 
/*
* Given a year, month and day in the Gregorian
* calendar, return a numeric date which is equal
* to the number of days since the start of the
* Common era
*/
serial_date: proc (yr, mo, da) returns (float bin);
dcl (yr, mo, da) float bin;
dcl n float bin;
n = 365 * yr + da + 31 * (mo - 1);
if (mo >= 3) then
n = n - fixed(0.4 * mo + 2.3);
else
yr = yr - 1;
n = n + fixed(yr/4) - fixed(0.75 * fixed(yr/100) + 1);
return (n);
end serial_date;
 
end elapsed_days;
</syntaxhighlight>
{{out}}
Test case taken from the Delphi example
<pre>
Elapsed Date Calculator
First date as YYYY-MM-DD : 1970-01-01
Second date as YYYY-MM-DD : 2019-10-18
Elapsed days = 18187
Do another (y/n)? n
</pre>
 
=={{header|PL/M}}==
{{Trans|FreeBASIC}}
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)<br>
Note that as the 8080 PL/M compiler only supports 8 and 16 bit unsigned integers, the dates must be at most 65535 days apart.
<syntaxhighlight lang="plm">
100H: /* CALCULATE THE NUMBER OF DAYS BETWEEN TWO DATES; BASED ON FREEBASIC */
 
/* CP/M BDOS SYSTEM CALL AND I/O ROUTINES */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
PR$SIGNED: PROCEDURE( N ); /* PRINTS N AS A SIGNED INTEGER */
DECLARE N ADDRESS;
IF N <= 32767
THEN CALL PR$NUMBER( N );
ELSE DO;
CALL PR$CHAR( '-' );
CALL PR$NUMBER( - N );
END;
END PR$SIGNED ;
 
/* TASK */
 
/* RETURNS THE GREGORIAN DAY CORRESPONDING TO YYYY/MM/DD */
GREGORIAN: PROCEDURE( YYYY$MM$DD )ADDRESS;
DECLARE YYYY$MM$DD ADDRESS;
DECLARE DATE BASED YYYY$MM$DD ( 10 )BYTE;
DECLARE ( YYYY, MM, DD, N, W ) ADDRESS;
 
DIGIT: PROCEDURE( D )BYTE; DECLARE D BYTE; RETURN D - '0'; END;
 
YYYY = ( DIGIT( DATE( 0 ) ) * 1000 ) + ( DIGIT( DATE( 1 ) ) * 100 )
+ ( DIGIT( DATE( 2 ) ) * 10 ) + DIGIT( DATE( 3 ) );
MM = ( DIGIT( DATE( 5 ) ) * 10 ) + DIGIT( DATE( 6 ) );
DD = ( DIGIT( DATE( 8 ) ) * 10 ) + DIGIT( DATE( 9 ) );
N = ( MM + 9 ) - ( ( ( MM + 9 ) / 12 ) * 12 );
W = YYYY - ( N / 10 );
RETURN ( 365 * W ) + ( W / 4 ) - ( W / 100 ) + ( W / 400 )
+ ( ( ( N * 306 ) + 5 ) / 10 ) + ( DD - 1 );
END GREGORIAN ;
 
/* SHOWS TTHE DAYS DIFFERENCE BETWEEN FROM$G AND TO$$G */
PR$DAYS$DIFFERENCE: PROCEDURE( FROM$DATE, TO$DATE );
DECLARE ( FROM$DATE, TO$DATE )ADDRESS;
CALL PR$STRING( .'DAYS BETWEEN $' );CALL PR$STRING( FROM$DATE );
CALL PR$STRING( .' AND $' );CALL PR$STRING( TO$DATE );
CALL PR$STRING( .' IS $' );
CALL PR$SIGNED( GREGORIAN( TO$DATE ) - GREGORIAN( FROM$DATE ) );
CALL PR$NL;
END PR$DAYS$DIFFERENCE ;
 
CALL PR$DAYS$DIFFERENCE( .'1902-01-01$', .'1968-12-25$' );
CALL PR$DAYS$DIFFERENCE( .'2019-01-01$', .'2019-01-02$' );
CALL PR$DAYS$DIFFERENCE( .'2019-01-02$', .'2019-01-01$' );
CALL PR$DAYS$DIFFERENCE( .'2019-01-01$', .'2019-03-01$' );
CALL PR$DAYS$DIFFERENCE( .'2020-01-01$', .'2020-03-01$' );
CALL PR$DAYS$DIFFERENCE( .'1995-11-21$', .'1995-11-21$' );
CALL PR$DAYS$DIFFERENCE( .'2090-01-01$', .'2098-12-25$' );
 
EOF
</syntaxhighlight>
{{out}}
<pre>
DAYS BETWEEN 1902-01-01 AND 1968-12-25 IS 24465
DAYS BETWEEN 2019-01-01 AND 2019-01-02 IS 1
DAYS BETWEEN 2019-01-02 AND 2019-01-01 IS -1
DAYS BETWEEN 2019-01-01 AND 2019-03-01 IS 59
DAYS BETWEEN 2020-01-01 AND 2020-03-01 IS 60
DAYS BETWEEN 1995-11-21 AND 1995-11-21 IS 0
DAYS BETWEEN 2090-01-01 AND 2098-12-25 IS 3280
</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
 
#!/usr/bin/python
Line 1,629 ⟶ 2,017:
two = sys.argv[2]
print diff(one,two)
</langsyntaxhighlight>
 
{{out}}
Line 1,637 ⟶ 2,025:
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
<lang QB64>
'Task
'Calculate the number of days between two dates.
Line 1,700 ⟶ 2,088:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Dates are first class objects in Raku and may have arithmetic in days done directly on them.
<syntaxhighlight lang="raku" perl6line>say Date.new('2019-09-30') - Date.new('2019-01-01');
 
say Date.new('2019-03-01') - Date.new('2019-02-01');
Line 1,719 ⟶ 2,107:
say Date.new('2019-02-29') + 30;
 
CATCH { default { .message.say; exit; } };</langsyntaxhighlight>
 
<pre>272
Line 1,744 ⟶ 2,132:
<br>days since the beginning of the Gregorian calendar, &nbsp; and &nbsp; '''I''' &nbsp; which is the option that indicates the date is in
<br>the &nbsp; '''ISO''' &nbsp; (International Standards Organization standard 8601:2004) &nbsp; format.
<langsyntaxhighlight lang="rexx">/*REXX program computes the number of days between two dates in the form of YYYY-MM-DD */
parse arg $1 $2 . /*get 2 arguments (dates) from the C.L.*/
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the inputs of: &nbsp; &nbsp; <tt> 2019-10-02 &nbsp; 2000-01-01 </tt>}}
<pre>
Line 1,768 ⟶ 2,156:
 
Also, more informative error messages are generated.
<langsyntaxhighlight lang="rexx">/*REXX program computes the number of days between two dates in the form of YYYY-MM-DD */
parse arg $.1 $.2 _ . 1 . . xtra /*obtain two arguments from the C.L. */
seps= '/-\'; yr.= .; mon.= .; dd.= . /*define the defaults for both dates. */
Line 1,824 ⟶ 2,212:
if length(yr.a)==2 then yr.a= left( date('S'), 2)yr.a /*2 dig yy ?*/
if yr.a==. | mon.a==. | dd.a==. then call serDAT /*validate. */
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the inputs of: &nbsp; &nbsp; <tt> * &nbsp; 2000-1-1 </tt>}}
 
Line 1,833 ⟶ 2,221:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 1,851 ⟶ 2,239:
? "Days between " + DaysBetween[n][1] + " and " + DaysBetween[n][2] + ": " + diffdays(date4,date3)
next
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,861 ⟶ 2,249:
Days between 1902-01-01 and 1968-12-25: 0
Days between 2090-01-01 and 2098-12-25: 3280
</pre>
 
=={{header|RPL}}==
Uses Python formula, in a forced binary calculation mode to avoid 'flooring' instructions
{{works with|Halcyon Calc|4.2.7}}
≪ → d m y
≪ m 9 + 12 MOD
y OVER #10d / -
DUP 365 * OVER #4d / + OVER #100d / - SWAP #400d / +
SWAP 306 * 5 + #10d / + d + 1 - B→R
≫ ≫
'GREGN' STO
≪ SWAP 1 2 '''START'''
→ date
≪ date 9 10 SUB STR→ date 6 7 SUB STR→ date 1 4 SUB STR→
GREGN SWAP
'''NEXT''' -
'NBDAYS' STO
 
"1902-01-01" "1968-12-25" NBDAYS
"2019-01-02" "2019-01-01" NBDAYS
"2019-01-01" "2019-03-01" NBDAYS
"2020-01-01" "2020-03-01" NBDAYS
{{out}}
<pre>
4: 24465
3: -1
2: 59
1: 60
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require "date"
 
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
Line 1,870 ⟶ 2,290:
p (d1 - d2).to_i # => -291
p (d2 - d1).to_i # => 291
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">// [dependencies]
// chrono = "0.4"
 
Line 1,896 ⟶ 2,316:
std::process::exit(1);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,902 ⟶ 2,322:
days_between_dates 2020-01-01 2020-09-06
249
</pre>
 
=={{header|S-BASIC}}==
Error checking of entered dates is omitted in order to focus
on the stated task but would obviously have to be included
in production code.
<syntaxhighlight lang = "BASIC">
comment
Given a month, day, and year in the Gregorian calendar,
return a numeric date which is equal to the number of
days since the start of the Common era.
end
function serial_date(da, mo, yr = integer) = real
var n = real
n = 365 * yr + da + 31 * (mo - 1)
if mo >= 3 then
n = n - int(.4 * mo + 2.3)
else
yr = yr - 1
n = n + int(yr/4) - int(.75 * (int(yr/100) + 1))
end = n
 
comment
Read a date in YYYY-MM-DD format from the console and
return its serial date equivalent.
end
function get_date = real
var date = string : 20
var y, m, d = integer
input2 date
y = val(mid(date,1,4))
m = val(mid(date,6,2))
d = val(mid(date,9,2))
end = serial_date(d, m, y)
 
rem -- main program begins here
 
var date1, date2 = real
var another = char
 
repeat
begin
print "First date : ";
date1 = get_date
print "Second date : ";
date2 = get_date
print "Elapsed days = "; date2 - date1
input "Do another (y/n)"; another
end
until not another
 
end
</syntaxhighlight>
{{out}}
Test dates taken from Delphi example
<pre>
First date : 1970-01-01
Second date : 2019-10-18
Elapsed days = 18187
Do another (y/n)? n
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object DaysBetweenDates {
 
/*Inspired by the Python version of the algorithm and the discussion here
Line 1,942 ⟶ 2,422:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,958 ⟶ 2,438:
=={{header|SenseTalk}}==
SenseTalk supports date and time calculations in many forms, and many different units of time (such as 'days' in this example). Rounding is needed due to daylight savings time changes.
<langsyntaxhighlight lang="sensetalk">set startDate to "2020-03-13"
set endDate to "2021-07-14"
 
put (endDate - startDate) rounded to nearest day
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,969 ⟶ 2,449:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">require('Date::Calc')
 
func days_diff(a,b) {
Line 1,983 ⟶ 2,463:
var days = days_diff(date1, date2)
 
say "There are #{days} days between these dates"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,993 ⟶ 2,473:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
func daysFromTimeInterval(_ interval: Double) -> Int {
Line 2,018 ⟶ 2,498:
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
 
print("There are \(days) days between \(start) and \(end)")</langsyntaxhighlight>
 
{{out}}
Line 2,029 ⟶ 2,509:
{{works with|Bourne Again Shell}}
 
<langsyntaxhighlight lang="bash"># return true if year is leap in Gregorian calendar
leap() {
local -i year
Line 2,064 ⟶ 2,544:
 
days_between 1970-01-01 2019-12-04
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,071 ⟶ 2,551:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System.Globalization
 
Module Module1
Line 2,085 ⟶ 2,565:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>18187</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">import time
 
fn days_between(d1 string, d2 string) ?int {
Line 2,107 ⟶ 2,587:
days = days_between(date1, date2)?
println("There are $days days between $date1 and $date2")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,115 ⟶ 2,595:
=={{header|Wren}}==
{{libheader|Wren-date}}
<langsyntaxhighlight ecmascriptlang="wren">import "./date" for Date
 
var datePairs = [
Line 2,130 ⟶ 2,610:
["2020-02-29", "2020-03-01"]
]
Date.default = Date.isoDate
for (dates in datePairs) {
var date1 = Date.parse(dates[0])
var date2 = Date.parse(dates[1])
var days = (date2 - date1).days
Date.default = Date.isoDate
System.print("Days between %(date1) and %(date2) = %(days)")
}</langsyntaxhighlight>
 
{{out}}
Line 2,151 ⟶ 2,631:
Days between 2019-03-29 and 2029-03-29 = 3653
Days between 2020-02-29 and 2020-03-01 = 1
</pre>
 
=={{header|XPL0}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang "XPL0">func Gregorian(Y, M, D); \Return Gregorian day given date
int Y, M, D;
int N, W;
[N:= M + 9 - (M+9)/12*12;
W:= Y - N/10;
return 365*W + W/4 - W/100 + W/400 + (N*306+5)/10 + D - 1;
];
 
int Dates, N, Y, M, D, G0, G1;
[Dates:= [
["2019-01-01", "2019-01-02"],
["2019-01-02", "2019-01-01"],
["2019-01-01", "2019-03-01"],
["2020-01-01", "2020-03-01"],
["1995-11-21", "1995-11-21"],
["2090-01-01", "2098-12-25"] ];
OpenO(8); OpenI(8);
for N:= 0 to 6-1 do
[Text(8, Dates(N,0));
Y:= IntIn(8); M:= IntIn(8); D:= IntIn(8);
G0:= Gregorian(Y, M, D);
Text(8, Dates(N,1));
Y:= IntIn(8); M:= IntIn(8); D:= IntIn(8);
G1:= Gregorian(Y, M, D);
Text(0, "Number of days between "); Text(0, Dates(N,0)); Text(0, " and ");
Text(0, Dates(N,1)); Text(0, " is "); IntOut(0, abs(G1-G0)); CrLf(0);
];
]</syntaxhighlight>
{{out}}
<pre>
Number of days between 2019-01-01 and 2019-01-02 is 1
Number of days between 2019-01-02 and 2019-01-01 is 1
Number of days between 2019-01-01 and 2019-03-01 is 59
Number of days between 2020-01-01 and 2020-03-01 is 60
Number of days between 1995-11-21 and 1995-11-21 is 0
Number of days between 2090-01-01 and 2098-12-25 is 3280
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var [const] TD=Time.Date;
today:=TD.parseDate("--"); // "yyyy-mm-dd" and variations --> (y,m,d)
// or Time.Clock.UTC --> (y,m,d,h,m,s)
Line 2,163 ⟶ 2,683:
TD.toYMDString(today.xplode()), // to(y,m,d) not to((y,m,d))
TD.toYMDString(then.xplode()),
TD.deltaDays(today,then.xplode())));</langsyntaxhighlight>
{{out}}
<pre>
44

edits