Days between dates: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 12:
=={{header|11l}}==
<
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())</
{{out}}
Line 26:
=={{header|Action!}}==
{{libheader|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</
{{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}}==
<
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;</
{{out}}
Line 182:
=={{header|AppleScript}}==
<
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")</
{{output}}
Line 229:
Or, composing a function from reusable generics, and drawing on NSISO8601DateFormatter:
<
use framework "Foundation"
use scripting additions
Line 360:
set my text item delimiters to dlm
str
end unlines</
{{Out}}
<pre>2020-04-11 -> 2001-01-01 -> -7040 days
Line 371:
{{trans|Ruby}}
<
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"
]</
{{out}}
Line 388:
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">db =
(
1995-11-21|1995-11-21
Line 412:
EnvSub, D2, % D1, days
return D2
}</
{{out}}
<pre>Days between 1995-11-21 and 1995-11-21 : 0 Day(s)
Line 424:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f DAYS_BETWEEN_DATES.AWK
BEGIN {
Line 466:
return(result)
}
</syntaxhighlight>
{{out}}
<pre>
Line 499:
=={{header|C}}==
<syntaxhighlight lang="c">
#include<stdbool.h>
#include<string.h>
Line 559:
return 0;
}
</syntaxhighlight>
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.
<
date ← {
o ← 719469
Line 593:
S2D←ToI¨ '-'⊸Split
DBw ← -○(date.From S2D)</
<pre> "2019-09-30" DBw "2019-01-01"
272</pre>
Line 600:
=={{header|C++}}==
{{trans|c}}
<
#include <iostream>
Line 736:
return 0;
}</
{{out}}
<pre>Days difference : 335</pre>
Line 742:
===Alternative using Boost===
{{libheader|Boost}}
<
#include <iostream>
#include <boost/date_time/gregorian/gregorian.hpp>
Line 761:
}
return EXIT_SUCCESS;
}</
{{out}}
Line 770:
=={{header|C sharp|C#}}==
<
using System.Globalization;
Line 782:
return (int)(b - a).TotalDays;
}
}</
{{out}}
<pre>
Line 791:
{{works with|GnuCOBOL}}
<
*> Tectonics: cobc -xj days-between.cob
Line 811:
goback.
end program days-between.</
{{out}}
Line 820:
=={{header|Commodore BASIC}}==
<syntaxhighlight 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>
Line 879:
=={{header|D}}==
<
import std.stdio;
Line 887:
auto diff = toDate - fromDate;
writeln("Number of days between ", fromDate, " and ", toDate, ": ", diff.total!"days");
}</
{{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">
program Days_between_dates;
Line 925:
Writeln(DaysBetween('1970-01-01', '2019-10-18'));
readln;
end.</
{{out}}
<pre>18187</pre>
=={{header|Erlang}}==
<
-module(daysbetween).
Line 952:
</
{{out}}
erlang shell:
Line 1,066:
=={{header|F_Sharp|F#}}==
<
// 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>
{{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.
<
: 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</
{{out}}
<pre>
Line 1,092:
=={{header|FreeBASIC}}==
<
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</
{{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.
<
d2 = # 2020-12-06 #
println[d1-d2 -> days]</
{{out}}
Line 1,156:
=={{header|Go}}==
<
import (
Line 1,193:
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}</
{{out}}
Line 1,203:
=={{header|Groovy}}==
{{trans|Kotlin}} {{trans|Java}}
<
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}"</
{{out}}
<pre>Number of days between 2019-01-01 and 2019-10-19: 291</pre>
=={{header|Haskell}}==
<
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</
{{out}}
<pre>There are 272 days between 2019-01-01 and 2019-09-30.
Line 1,239:
Or, composing rather than raising errors:
<
import Data.Time.Calendar (diffDays)
import Data.Time.Format (defaultTimeLocale, parseTimeM)
Line 1,281:
]
)
$ daysBetween s1 s2</
{{Out}}
<pre>There are 272 days between 2019-01-01 and 2019-09-30.
Line 1,304:
=={{header|Java}}==
{{trans|Kotlin}}
<
import java.time.temporal.ChronoUnit;
Line 1,314:
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}</
{{out}}
<pre>Number of days between 2019-01-01 and 2019-10-19: 291</pre>
=={{header|JavaScript}}==
<
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'));</
{{out}}
<pre>Days between 2021-10-27 and 2020-03-03: 603</pre>
Line 1,337:
===Using jq's built-ins===
<syntaxhighlight lang="jq">
def days_between(yyyymmddBefore; yyyymmddAfter):
(yyyymmddBefore | strptime("%Y-%m-%d") | mktime) as $before
Line 1,367:
task
</syntaxhighlight>
{{out}}
<pre>
Line 1,389:
===From first principles===
'''Adapted from [[#Wren|Wren]]'''
<syntaxhighlight 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>
'''The Tasks'''
Line 1,441:
=={{header|Julia}}==
<
@show Day(DateTime("2019-09-30") - DateTime("2019-01-01"))
Line 1,450:
@show Day(DateTime("2029-03-29") - DateTime("2019-03-29"))
</
<pre>
Day(DateTime("2019-09-30") - DateTime("2019-01-01")) = 272 days
Line 1,459:
=={{header|Kotlin}}==
<
import java.time.temporal.ChronoUnit
Line 1,467:
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}</
{{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.
<
-- 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.")</
{{out}}
<pre>Enter date 1: 1970-01-01
Line 1,494:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
DateDifference["2021-01-01", "2021-03-01"]</
{{out}}
<pre>Quantity[60, "Days"]
Line 1,501:
=={{header|Nim}}==
<
proc daysBetween(date1, date2: string): int64 =
Line 1,516:
for (date1, date2) in Dates:
echo "Days between ", date1, " and ", date2, ": ", daysBetween(date1, date2)</
{{out}}
Line 1,529:
=={{header|Perl}}==
Would not reinvent this wheel.
<
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</
{{out}}
<pre>427
Line 1,546:
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<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;">)
<!--</
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}}==
<
(abs (- ($dat A "-") ($dat B "-"))) )
(println (diffDates "2019-1-1" "2019-9-30"))
(println (diffDates "2015-12-31" "2016-09-30"))</
{{out}}
<pre>
Line 1,597:
=={{header|Python}}==
<
#!/usr/bin/python
Line 1,629:
two = sys.argv[2]
print diff(one,two)
</
{{out}}
Line 1,637:
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
'Task
'Calculate the number of days between two dates.
Line 1,700:
</syntaxhighlight>
=={{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"
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; } };</
<pre>272
Line 1,744:
<br>days since the beginning of the Gregorian calendar, and '''I''' which is the option that indicates the date is in
<br>the '''ISO''' (International Standards Organization standard 8601:2004) format.
<
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. */</
{{out|output|text= when using the inputs of: <tt> 2019-10-02 2000-01-01 </tt>}}
<pre>
Line 1,768:
Also, more informative error messages are generated.
<
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</
{{out|output|text= when using the inputs of: <tt> * 2000-1-1 </tt>}}
Line 1,833:
=={{header|Ring}}==
<
load "stdlib.ring"
Line 1,851:
? "Days between " + DaysBetween[n][1] + " and " + DaysBetween[n][2] + ": " + diffdays(date4,date3)
next
</syntaxhighlight>
{{out}}
<pre>
Line 1,864:
=={{header|Ruby}}==
<
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>
=={{header|Rust}}==
<
// chrono = "0.4"
Line 1,896:
std::process::exit(1);
}
}</
{{out}}
Line 1,905:
=={{header|Scala}}==
<
/*Inspired by the Python version of the algorithm and the discussion here
Line 1,942:
}
</syntaxhighlight>
{{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.
<
set endDate to "2021-07-14"
put (endDate - startDate) rounded to nearest day
</syntaxhighlight>
{{out}}
<pre>
Line 1,969:
=={{header|Sidef}}==
<
func days_diff(a,b) {
Line 1,983:
var days = days_diff(date1, date2)
say "There are #{days} days between these dates"</
{{out}}
<pre>
Line 1,993:
=={{header|Swift}}==
<
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)")</
{{out}}
Line 2,029:
{{works with|Bourne Again Shell}}
<
leap() {
local -i year
Line 2,064:
days_between 1970-01-01 2019-12-04
</syntaxhighlight>
{{Out}}
Line 2,071:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Module Module1
Line 2,085:
End Sub
End Module</
{{out}}
<pre>18187</pre>
Line 2,091:
=={{header|Vlang}}==
{{trans|go}}
<
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")
}</
{{out}}
<pre>
Line 2,115:
=={{header|Wren}}==
{{libheader|Wren-date}}
<
var datePairs = [
Line 2,136:
Date.default = Date.isoDate
System.print("Days between %(date1) and %(date2) = %(days)")
}</
{{out}}
Line 2,154:
=={{header|zkl}}==
<
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())));</
{{out}}
<pre>
|