Days between dates: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
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 182:
=={{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:
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:
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:
set my text item delimiters to dlm
str
end unlines</langsyntaxhighlight>
{{Out}}
<pre>2020-04-11 -> 2001-01-01 -> -7040 days
Line 371:
{{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:
"days between the two dates:"
daysBetweenDates "01/01/2019" "19/10/2019"
]</langsyntaxhighlight>
 
{{out}}
Line 388:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">db =
<lang AutoHotkey>db =
(
1995-11-21|1995-11-21
Line 412:
EnvSub, D2, % D1, days
return D2
}</langsyntaxhighlight>
{{out}}
<pre>Days between 1995-11-21 and 1995-11-21 : 0 Day(s)
Line 424:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DAYS_BETWEEN_DATES.AWK
BEGIN {
Line 466:
return(result)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 499:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include<stdbool.h>
#include<string.h>
Line 559:
return 0;
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 570:
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:
 
S2D←ToI¨ '-'⊸Split
DBw ← -○(date.From S2D)</langsyntaxhighlight>
<pre> "2019-09-30" DBw "2019-01-01"
272</pre>
Line 600:
=={{header|C++}}==
{{trans|c}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
 
Line 736:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Days difference : 335</pre>
Line 742:
===Alternative using Boost===
{{libheader|Boost}}
<langsyntaxhighlight lang="cpp">#include <cstdlib>
#include <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>
Line 761:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
Line 770:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Globalization;
 
Line 782:
return (int)(b - a).TotalDays;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 791:
{{works with|GnuCOBOL}}
 
<langsyntaxhighlight COBOLlang="cobol">COBOL *> days-between
*> Tectonics: cobc -xj days-between.cob
 
Line 811:
 
goback.
end program days-between.</langsyntaxhighlight>
 
{{out}}
Line 820:
 
=={{header|Commodore BASIC}}==
<syntaxhighlight lang="gwbasic">
<lang GWBasic>
100 REM ===============================
110 REM DAYS BETWEEN 2 DATES
Line 872:
9080 G=G+INT((N*306+5)/10)+(D-1)
9090 RETURN
</syntaxhighlight>
</lang>
 
 
Line 879:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.datetime.date;
import std.stdio;
 
Line 887:
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:
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Days_between_dates;
 
Line 925:
Writeln(DaysBetween('1970-01-01', '2019-10-18'));
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>18187</pre>
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
 
-module(daysbetween).
Line 952:
 
</langsyntaxhighlight>
{{out}}
erlang shell:
Line 1,066:
 
=={{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:
=={{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:
 
"2019-01-01" "2019-09-30" days-between .
"2016-01-01" "2016-09-30" days-between . ! leap year</langsyntaxhighlight>
{{out}}
<pre>
Line 1,092:
 
=={{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:
Print Using "##### days"; (G2-G1)
Next n
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 1,139:
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,156:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,193:
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}</langsyntaxhighlight>
 
{{out}}
Line 1,203:
=={{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:
 
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:
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:
]
)
$ daysBetween s1 s2</langsyntaxhighlight>
{{Out}}
<pre>There are 272 days between 2019-01-01 and 2019-09-30.
Line 1,304:
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="java">import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
 
Line 1,314:
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:
 
===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:
 
task
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,389:
===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:
| (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:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Dates
 
@show Day(DateTime("2019-09-30") - DateTime("2019-01-01"))
Line 1,450:
@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:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">import java.time.LocalDate
import java.time.temporal.ChronoUnit
 
Line 1,467:
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:
=={{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:
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
Line 1,494:
 
=={{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:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import times
 
proc daysBetween(date1, date2: string): int64 =
Line 1,516:
 
for (date1, date2) in Dates:
echo "Days between ", date1, " and ", date2, ": ", daysBetween(date1, date2)</langsyntaxhighlight>
 
{{out}}
Line 1,529:
=={{header|Perl}}==
Would not reinvent this wheel.
<langsyntaxhighlight lang="perl">use feature 'say';
use Date::Calc qw(Delta_Days);
 
Line 1,536:
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:
=={{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:
<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:
 
=={{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,597:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">
 
#!/usr/bin/python
Line 1,629:
two = sys.argv[2]
print diff(one,two)
</langsyntaxhighlight>
 
{{out}}
Line 1,637:
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
<lang QB64>
'Task
'Calculate the number of days between two dates.
Line 1,700:
 
 
</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:
say Date.new('2019-02-29') + 30;
 
CATCH { default { .message.say; exit; } };</langsyntaxhighlight>
 
<pre>272
Line 1,744:
<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:
 
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:
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:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 1,851:
? "Days between " + DaysBetween[n][1] + " and " + DaysBetween[n][2] + ": " + diffdays(date4,date3)
next
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,864:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require "date"
 
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
Line 1,870:
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:
std::process::exit(1);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,905:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object DaysBetweenDates {
 
/*Inspired by the Python version of the algorithm and the discussion here
Line 1,942:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,958:
=={{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:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">require('Date::Calc')
 
func days_diff(a,b) {
Line 1,983:
var days = days_diff(date1, date2)
 
say "There are #{days} days between these dates"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,993:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">import Foundation
 
func daysFromTimeInterval(_ interval: Double) -> Int {
Line 2,018:
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
 
print("There are \(days) days between \(start) and \(end)")</langsyntaxhighlight>
 
{{out}}
Line 2,029:
{{works with|Bourne Again Shell}}
 
<langsyntaxhighlight lang="bash"># return true if year is leap in Gregorian calendar
leap() {
local -i year
Line 2,064:
 
days_between 1970-01-01 2019-12-04
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,071:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System.Globalization
 
Module Module1
Line 2,085:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>18187</pre>
Line 2,091:
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="vlang">import time
 
fn days_between(d1 string, d2 string) ?int {
Line 2,107:
days = days_between(date1, date2)?
println("There are $days days between $date1 and $date2")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,115:
=={{header|Wren}}==
{{libheader|Wren-date}}
<langsyntaxhighlight lang="ecmascript">import "/date" for Date
 
var datePairs = [
Line 2,136:
Date.default = Date.isoDate
System.print("Days between %(date1) and %(date2) = %(days)")
}</langsyntaxhighlight>
 
{{out}}
Line 2,154:
 
=={{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:
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>
10,333

edits