How to find the difference in days between two dates?












63















A="2002-20-10"

B="2003-22-11"



How to find the difference in days between two dates?










share|improve this question




















  • 3





    As explained below, but your dates are the wrong way round: they need to be yyyy-mm-dd

    – Peter Flynn
    Nov 8 '17 at 9:12
















63















A="2002-20-10"

B="2003-22-11"



How to find the difference in days between two dates?










share|improve this question




















  • 3





    As explained below, but your dates are the wrong way round: they need to be yyyy-mm-dd

    – Peter Flynn
    Nov 8 '17 at 9:12














63












63








63


15






A="2002-20-10"

B="2003-22-11"



How to find the difference in days between two dates?










share|improve this question
















A="2002-20-10"

B="2003-22-11"



How to find the difference in days between two dates?







bash shell date






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 11 '18 at 20:27









codeforester

17.6k84064




17.6k84064










asked Feb 9 '11 at 15:17









TreeTree

3,293215581




3,293215581








  • 3





    As explained below, but your dates are the wrong way round: they need to be yyyy-mm-dd

    – Peter Flynn
    Nov 8 '17 at 9:12














  • 3





    As explained below, but your dates are the wrong way round: they need to be yyyy-mm-dd

    – Peter Flynn
    Nov 8 '17 at 9:12








3




3





As explained below, but your dates are the wrong way round: they need to be yyyy-mm-dd

– Peter Flynn
Nov 8 '17 at 9:12





As explained below, but your dates are the wrong way round: they need to be yyyy-mm-dd

– Peter Flynn
Nov 8 '17 at 9:12












17 Answers
17






active

oldest

votes


















24














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.



Or you need a portable way?






share|improve this answer
























  • yes i need portable way

    – Tree
    Feb 9 '11 at 15:46











  • @Tree: I believe there is no portable way to subtract dates short of implementing it yourself — it's not that hard, the only thing of interest are leap years. But nowadays everyone wants to subtract dates, as it seems: Have a look at unix.stackexchange.com/questions/1825/… :)

    – user332325
    Feb 9 '11 at 20:29






  • 7





    For lazyweb's sake, I think this is what user332325 meant: echo "( `date -d $B +%s` - `date -d $A +%s`) / (24*3600)" | bc -l

    – Pablo Mendes
    May 6 '15 at 16:43








  • 1





    What does portable mean in this context?

    – htellez
    Feb 20 '16 at 0:22











  • @htellez something that works on multiple platforms (windows, linux etc..)

    – Anubis
    Feb 28 '18 at 12:50



















50














The bash way - convert the dates into %y%m%d format and then you can do this straight from the command line:



echo $(( ($(date --date="031122" +%s) - $(date --date="021020" +%s) )/(60*60*24) ))





share|improve this answer





















  • 9





    This doesn't necessarily need the dates to be in %y%m%d format. E.g. gnu date will accept the %Y-%m-%d format the OP used. In general, ISO-8601 is a good choice (and the OP's format is one such format). Formats with 2 digit years are better avoided.

    – mc0e
    Jun 16 '15 at 11:52






  • 2





    For the difference from today, one may like to use days_diff=$(( (`date -d $B +%s` - `date -d "00:00" +%s`) / (24*3600) )). note that $days_diff will be an integer (i.e. no decimals)

    – Julien
    Jan 7 '16 at 10:41











  • This is dependent on the variant of date installed. It works for GNU date. It doesn't work with POSIX date. This probably isn't a problem for most readers, but it's worth noting.

    – mc0e
    Mar 1 '18 at 15:01











  • If you really want POSIX portability, check this: unix.stackexchange.com/a/7220/43835

    – mc0e
    Mar 1 '18 at 15:05





















14














And in python



$python -c "from datetime import date; print (date(2003,11,22)-date(2002,10,20)).days"
398





share|improve this answer



















  • 2





    +1 This is the most portable way.

    – mouviciel
    Oct 11 '13 at 8:03











  • @mouviciel not really. Python is not always present.

    – mc0e
    Jun 16 '15 at 11:57











  • @mc0e in that context, nothing is always present

    – Anubis
    Feb 28 '18 at 12:53








  • 1





    @Anubis the OP specified tags as bash and shell, so I think we can assume that we're talking about a *nix system. Within such systems, echo and date are reliably present, but python is not.

    – mc0e
    Mar 1 '18 at 14:53













  • @mc0e yeah that makes sense. Even-though python2 is available in most *nix systems, when it comes to low-end devices (embedded etc..) we will have to survive only with primary tools.

    – Anubis
    Mar 2 '18 at 10:06



















14














Watch out! Many of the bash solutions here are broken for date ranges which span the date when daylight savings time begins (where applicable). This is because the $(( math )) construct does a 'floor'/truncation operation on the resulting value, returning only the whole number. Let me illustrate:



DST started March 8th this year in the US, so let's use a date range spanning that:



start_ts=$(date -d "2015-03-05" '+%s')
end_ts=$(date -d "2015-03-11" '+%s')


Let's see what we get with the double parentheses:



echo $(( ( end_ts - start_ts )/(60*60*24) ))


Returns '5'.



Doing this using 'bc' with more accuracy gives us a different result:



echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc


Returns '5.95' - the missing 0.05 being the lost hour from the DST switchover.



So how should this be done correctly?

I would suggest using this instead:



printf "%.0f" $(echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc)


Here, the 'printf' rounds the more accurate result calculated by 'bc', giving us the correct date range of '6'.



Edit: highlighting the answer in a comment from @hank-schultz below, which I have been using lately:



date_diff=$(( ($(date -d "2015-03-11 UTC" +%s) - $(date -d "2015-03-05 UTC" +%s) )/(60*60*24) ))


This should also be leap second safe as long as you always subtract the earlier date from the later one, since leap seconds will only ever add to the difference - truncation effectively rounds down to the correct result.






share|improve this answer





















  • 3





    If instead, you specify the timezone for both the start and the end (and make sure they are the same), then you also no longer have this problem, like so: echo $(( ($(date --date="2015-03-11 UTC" +%s) - $(date --date="2015-03-05 UTC" +%s) )/(60*60*24) )), which returns 6, instead of 5.

    – Hank Schultz
    Jun 23 '15 at 20:40








  • 1





    Ah, one of the answerers thought about the inaccuracies of the basic solution repeated by others in variants. Thumbs up! How about leap seconds? It is leap-second-safe? There are precedents of software returning off-by-one-day result if run at certain times, ref problems associated with the leap second.

    – Stéphane Gourichon
    Nov 20 '15 at 12:29











  • Woops, the "wrong" computation you give as example correctly returns 6 here (Ubuntu 15.04 AMD64, GNU date version 8.23). Perhaps your example is timezone-dependant? My timezone is "Europe/Paris".

    – Stéphane Gourichon
    Nov 20 '15 at 12:34











  • Same good result for the "wrong" computation with GNU date 2.0 on MSYS, same timezone.

    – Stéphane Gourichon
    Nov 20 '15 at 12:35






  • 1





    @StéphaneGourichon, your timezone's daylight savings change looks to have happened on March 29, 2015 - so try a date range which includes that.

    – evan_b
    Dec 4 '15 at 22:22



















6














Here's the MAC OS X version for your convenience.



$ A="2002-20-10"; B="2003-22-11";
$ echo $(((`date -jf %Y-%d-%m $B +%s` - `date -jf %Y-%d-%m $A +%s`)/86400))


nJoy!






share|improve this answer





















  • 1





    -bash: ( - )/86400: syntax error: operand expected (error token is ")/86400")

    – cavalcade
    Nov 1 '16 at 0:56






  • 1





    @cavalcade - that is because you haven't done A="2002-20-10"; B="2003-22-11"

    – RAM237
    Jul 5 '17 at 13:43













  • Thanks, despite it works for this particular case, I would suggest using echo $(((`date -jf "%Y-%d-%m" "$B" +%s` - `date -jf "%Y-%d-%m" "$A" +%s`)/86400)), i.e. wrapping both formats and variables into double quotes, otherwise may fail on different date format (e.g. %b %d, %Y/Jul 5, 2017)

    – RAM237
    Jul 5 '17 at 13:46













  • @RAM237 Thats what I get for not paying attention headsmack Well spotted, thanks

    – cavalcade
    May 16 '18 at 12:54



















4














If the option -d works in your system, here's another way to do it. There is a caveat that it wouldn't account for leap years since I've considered 365 days per year.



date1yrs=`date -d "20100209" +%Y`
date1days=`date -d "20100209" +%j`
date2yrs=`date +%Y`
date2days=`date +%j`
diffyr=`expr $date2yrs - $date1yrs`
diffyr2days=`expr $diffyr * 365`
diffdays=`expr $date2days - $date1days`
echo `expr $diffyr2days + $diffdays`





share|improve this answer































    4














    Even if you don't have GNU date, you'll probably have Perl installed:



    use Time::Local;
    sub to_epoch {
    my ($t) = @_;
    my ($y, $d, $m) = ($t =~ /(d{4})-(d{2})-(d{2})/);
    return timelocal(0, 0, 0, $d+0, $m-1, $y-1900);
    }
    sub diff_days {
    my ($t1, $t2) = @_;
    return (abs(to_epoch($t2) - to_epoch($t1))) / 86400;
    }
    print diff_days("2002-20-10", "2003-22-11"), "n";


    This returns 398.041666666667 -- 398 days and one hour due to daylight savings.





    The question came back up on my feed. Here's a more concise method using a Perl bundled module



    days=$(perl -MDateTime -le '
    sub parse_date {
    @f = split /-/, shift;
    return DateTime->new(year=>$f[0], month=>$f[2], day=>$f[1]);
    }
    print parse_date(shift)->delta_days(parse_date(shift))->in_units("days");
    ' $A $B)
    echo $days # => 398





    share|improve this answer

































      2














      This works for me:



      A="2002-10-20"
      B="2003-11-22"
      echo $(( ($(date -d $B +%s) - $(date -d $A +%s)) / 86400 )) days


      Prints



      398 days


      What is happening?




      1. Provide valid time string in A and B

      2. Use date -d to handle time strings

      3. Use date %s to convert time strings to seconds since 1970 (unix epoche)

      4. Use bash parameter expansion to subtract seconds

      5. divide by seconds per day (86400=60*60*24) to get difference as days

      6. ! DST is not taken into account ! See this answer at unix.stackexchange!






      share|improve this answer

































        1














        I'd submit another possible solution in Ruby. Looks like it's the be smallest and cleanest looking one so far:



        A=2003-12-11
        B=2002-10-10
        DIFF=$(ruby -rdate -e "puts Date.parse('$A') - Date.parse('$B')")
        echo $DIFF





        share|improve this answer



















        • 1





          He is looking for a way in bash.

          – Cojones
          Mar 7 '12 at 11:26






        • 2





          There is no portable way to do it in shell itself. All alternatives use particular external programs (i.e. GNU date or some scripting language) and I honestly think that Ruby is a good way to go here. This solution is very short and does not use any non-standard libraries or other dependencies. In fact, I think that there's a higher chance of having Ruby installed than one would have GNU date installed.

          – GreyCat
          Mar 8 '12 at 21:14



















        1














        on unix you should have GNU dates installed. you do not need to deviate from bash. here is the strung out solution considering days, just to show the steps. it can be simplified and extended to full dates.



        DATE=$(echo `date`)
        DATENOW=$(echo `date -d "$DATE" +%j`)
        DATECOMING=$(echo `date -d "20131220" +%j`)
        THEDAY=$(echo `expr $DATECOMING - $DATENOW`)

        echo $THEDAY





        share|improve this answer

































          0














          Give this a try:



          perl -e 'use Date::Calc qw(Delta_Days); printf "%dn", Delta_Days(2002,10,20,2003,11,22);'





          share|improve this answer































            0














            Another Python version:



            python -c "from datetime import date; print date(2003, 11, 22).toordinal() - date(2002, 10, 20).toordinal()"





            share|improve this answer































              0














              Assume we rsync Oracle DB backups to a tertiary disk manually. Then we want to delete old backups on that disk. So here is a small bash script:



              #!/bin/sh

              for backup_dir in {'/backup/cmsprd/local/backupset','/backup/cmsprd/local/autobackup','/backup/cfprd/backupset','/backup/cfprd/autobackup'}
              do

              for f in `find $backup_dir -type d -regex '.*_.*_.*' -printf "%fn"`
              do

              f2=`echo $f | sed -e 's/_//g'`
              days=$(((`date "+%s"` - `date -d "${f2}" "+%s"`)/86400))

              if [ $days -gt 30 ]; then
              rm -rf $backup_dir/$f
              fi

              done

              done


              Modify the dirs and retention period ("30 days") to suit your needs.






              share|improve this answer


























              • Oracle puts backup sets in Flash Recovery Area using format like 'YYYY_MM_DD' so we delete the underscores for passing it to 'date -d'

                – Alex Cherkas
                Feb 18 '13 at 8:52





















              0














              Use the shell functions from http://cfajohnson.com/shell/ssr/ssr-scripts.tar.gz; they work in any standard Unix shell.



              date1=2012-09-22
              date2=2013-01-31
              . date-funcs-sh
              _date2julian "$date1"
              jd1=$_DATE2JULIAN
              _date2julian "$date2"
              echo $(( _DATE2JULIAN - jd1 ))


              See the documentation at http://cfajohnson.com/shell/ssr/08-The-Dating-Game.shtml






              share|improve this answer

































                0














                Using mysql command



                $ echo "select datediff('2013-06-20 18:12:54+08:00', '2013-05-30 18:12:54+08:00');"  | mysql -N


                Result: 21



                NOTE: Only the date parts of the values are used in the calculation



                Reference: http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_datediff






                share|improve this answer































                  0














                  This assumes that a month is 1/12 of a year:



                  #!/usr/bin/awk -f
                  function mktm(datespec) {
                  split(datespec, q, "-")
                  return q[1] * 365.25 + q[3] * 365.25 / 12 + q[2]
                  }
                  BEGIN {
                  printf "%dn", mktm(ARGV[2]) - mktm(ARGV[1])
                  }





                  share|improve this answer































                    0














                    For MacOS sierra (maybe from Mac OS X yosemate),



                    To get epoch time(Seconds from 1970) from a file, and save it to a var:

                    old_dt=`date -j -r YOUR_FILE "+%s"`



                    To get epoch time of current time

                    new_dt=`date -j "+%s"`



                    To calculate difference of above two epoch time

                    (( diff = new_dt - old_dt ))



                    To check if diff is more than 23 days

                    (( new_dt - old_dt > (23*86400) )) && echo Is more than 23 days






                    share|improve this answer























                      Your Answer






                      StackExchange.ifUsing("editor", function () {
                      StackExchange.using("externalEditor", function () {
                      StackExchange.using("snippets", function () {
                      StackExchange.snippets.init();
                      });
                      });
                      }, "code-snippets");

                      StackExchange.ready(function() {
                      var channelOptions = {
                      tags: "".split(" "),
                      id: "1"
                      };
                      initTagRenderer("".split(" "), "".split(" "), channelOptions);

                      StackExchange.using("externalEditor", function() {
                      // Have to fire editor after snippets, if snippets enabled
                      if (StackExchange.settings.snippets.snippetsEnabled) {
                      StackExchange.using("snippets", function() {
                      createEditor();
                      });
                      }
                      else {
                      createEditor();
                      }
                      });

                      function createEditor() {
                      StackExchange.prepareEditor({
                      heartbeatType: 'answer',
                      autoActivateHeartbeat: false,
                      convertImagesToLinks: true,
                      noModals: true,
                      showLowRepImageUploadWarning: true,
                      reputationToPostImages: 10,
                      bindNavPrevention: true,
                      postfix: "",
                      imageUploader: {
                      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                      allowUrls: true
                      },
                      onDemand: true,
                      discardSelector: ".discard-answer"
                      ,immediatelyShowMarkdownHelp:true
                      });


                      }
                      });














                      draft saved

                      draft discarded


















                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4946785%2fhow-to-find-the-difference-in-days-between-two-dates%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown

























                      17 Answers
                      17






                      active

                      oldest

                      votes








                      17 Answers
                      17






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      24














                      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.



                      Or you need a portable way?






                      share|improve this answer
























                      • yes i need portable way

                        – Tree
                        Feb 9 '11 at 15:46











                      • @Tree: I believe there is no portable way to subtract dates short of implementing it yourself — it's not that hard, the only thing of interest are leap years. But nowadays everyone wants to subtract dates, as it seems: Have a look at unix.stackexchange.com/questions/1825/… :)

                        – user332325
                        Feb 9 '11 at 20:29






                      • 7





                        For lazyweb's sake, I think this is what user332325 meant: echo "( `date -d $B +%s` - `date -d $A +%s`) / (24*3600)" | bc -l

                        – Pablo Mendes
                        May 6 '15 at 16:43








                      • 1





                        What does portable mean in this context?

                        – htellez
                        Feb 20 '16 at 0:22











                      • @htellez something that works on multiple platforms (windows, linux etc..)

                        – Anubis
                        Feb 28 '18 at 12:50
















                      24














                      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.



                      Or you need a portable way?






                      share|improve this answer
























                      • yes i need portable way

                        – Tree
                        Feb 9 '11 at 15:46











                      • @Tree: I believe there is no portable way to subtract dates short of implementing it yourself — it's not that hard, the only thing of interest are leap years. But nowadays everyone wants to subtract dates, as it seems: Have a look at unix.stackexchange.com/questions/1825/… :)

                        – user332325
                        Feb 9 '11 at 20:29






                      • 7





                        For lazyweb's sake, I think this is what user332325 meant: echo "( `date -d $B +%s` - `date -d $A +%s`) / (24*3600)" | bc -l

                        – Pablo Mendes
                        May 6 '15 at 16:43








                      • 1





                        What does portable mean in this context?

                        – htellez
                        Feb 20 '16 at 0:22











                      • @htellez something that works on multiple platforms (windows, linux etc..)

                        – Anubis
                        Feb 28 '18 at 12:50














                      24












                      24








                      24







                      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.



                      Or you need a portable way?






                      share|improve this answer













                      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.



                      Or you need a portable way?







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Feb 9 '11 at 15:26







                      user332325




















                      • yes i need portable way

                        – Tree
                        Feb 9 '11 at 15:46











                      • @Tree: I believe there is no portable way to subtract dates short of implementing it yourself — it's not that hard, the only thing of interest are leap years. But nowadays everyone wants to subtract dates, as it seems: Have a look at unix.stackexchange.com/questions/1825/… :)

                        – user332325
                        Feb 9 '11 at 20:29






                      • 7





                        For lazyweb's sake, I think this is what user332325 meant: echo "( `date -d $B +%s` - `date -d $A +%s`) / (24*3600)" | bc -l

                        – Pablo Mendes
                        May 6 '15 at 16:43








                      • 1





                        What does portable mean in this context?

                        – htellez
                        Feb 20 '16 at 0:22











                      • @htellez something that works on multiple platforms (windows, linux etc..)

                        – Anubis
                        Feb 28 '18 at 12:50



















                      • yes i need portable way

                        – Tree
                        Feb 9 '11 at 15:46











                      • @Tree: I believe there is no portable way to subtract dates short of implementing it yourself — it's not that hard, the only thing of interest are leap years. But nowadays everyone wants to subtract dates, as it seems: Have a look at unix.stackexchange.com/questions/1825/… :)

                        – user332325
                        Feb 9 '11 at 20:29






                      • 7





                        For lazyweb's sake, I think this is what user332325 meant: echo "( `date -d $B +%s` - `date -d $A +%s`) / (24*3600)" | bc -l

                        – Pablo Mendes
                        May 6 '15 at 16:43








                      • 1





                        What does portable mean in this context?

                        – htellez
                        Feb 20 '16 at 0:22











                      • @htellez something that works on multiple platforms (windows, linux etc..)

                        – Anubis
                        Feb 28 '18 at 12:50

















                      yes i need portable way

                      – Tree
                      Feb 9 '11 at 15:46





                      yes i need portable way

                      – Tree
                      Feb 9 '11 at 15:46













                      @Tree: I believe there is no portable way to subtract dates short of implementing it yourself — it's not that hard, the only thing of interest are leap years. But nowadays everyone wants to subtract dates, as it seems: Have a look at unix.stackexchange.com/questions/1825/… :)

                      – user332325
                      Feb 9 '11 at 20:29





                      @Tree: I believe there is no portable way to subtract dates short of implementing it yourself — it's not that hard, the only thing of interest are leap years. But nowadays everyone wants to subtract dates, as it seems: Have a look at unix.stackexchange.com/questions/1825/… :)

                      – user332325
                      Feb 9 '11 at 20:29




                      7




                      7





                      For lazyweb's sake, I think this is what user332325 meant: echo "( `date -d $B +%s` - `date -d $A +%s`) / (24*3600)" | bc -l

                      – Pablo Mendes
                      May 6 '15 at 16:43







                      For lazyweb's sake, I think this is what user332325 meant: echo "( `date -d $B +%s` - `date -d $A +%s`) / (24*3600)" | bc -l

                      – Pablo Mendes
                      May 6 '15 at 16:43






                      1




                      1





                      What does portable mean in this context?

                      – htellez
                      Feb 20 '16 at 0:22





                      What does portable mean in this context?

                      – htellez
                      Feb 20 '16 at 0:22













                      @htellez something that works on multiple platforms (windows, linux etc..)

                      – Anubis
                      Feb 28 '18 at 12:50





                      @htellez something that works on multiple platforms (windows, linux etc..)

                      – Anubis
                      Feb 28 '18 at 12:50













                      50














                      The bash way - convert the dates into %y%m%d format and then you can do this straight from the command line:



                      echo $(( ($(date --date="031122" +%s) - $(date --date="021020" +%s) )/(60*60*24) ))





                      share|improve this answer





















                      • 9





                        This doesn't necessarily need the dates to be in %y%m%d format. E.g. gnu date will accept the %Y-%m-%d format the OP used. In general, ISO-8601 is a good choice (and the OP's format is one such format). Formats with 2 digit years are better avoided.

                        – mc0e
                        Jun 16 '15 at 11:52






                      • 2





                        For the difference from today, one may like to use days_diff=$(( (`date -d $B +%s` - `date -d "00:00" +%s`) / (24*3600) )). note that $days_diff will be an integer (i.e. no decimals)

                        – Julien
                        Jan 7 '16 at 10:41











                      • This is dependent on the variant of date installed. It works for GNU date. It doesn't work with POSIX date. This probably isn't a problem for most readers, but it's worth noting.

                        – mc0e
                        Mar 1 '18 at 15:01











                      • If you really want POSIX portability, check this: unix.stackexchange.com/a/7220/43835

                        – mc0e
                        Mar 1 '18 at 15:05


















                      50














                      The bash way - convert the dates into %y%m%d format and then you can do this straight from the command line:



                      echo $(( ($(date --date="031122" +%s) - $(date --date="021020" +%s) )/(60*60*24) ))





                      share|improve this answer





















                      • 9





                        This doesn't necessarily need the dates to be in %y%m%d format. E.g. gnu date will accept the %Y-%m-%d format the OP used. In general, ISO-8601 is a good choice (and the OP's format is one such format). Formats with 2 digit years are better avoided.

                        – mc0e
                        Jun 16 '15 at 11:52






                      • 2





                        For the difference from today, one may like to use days_diff=$(( (`date -d $B +%s` - `date -d "00:00" +%s`) / (24*3600) )). note that $days_diff will be an integer (i.e. no decimals)

                        – Julien
                        Jan 7 '16 at 10:41











                      • This is dependent on the variant of date installed. It works for GNU date. It doesn't work with POSIX date. This probably isn't a problem for most readers, but it's worth noting.

                        – mc0e
                        Mar 1 '18 at 15:01











                      • If you really want POSIX portability, check this: unix.stackexchange.com/a/7220/43835

                        – mc0e
                        Mar 1 '18 at 15:05
















                      50












                      50








                      50







                      The bash way - convert the dates into %y%m%d format and then you can do this straight from the command line:



                      echo $(( ($(date --date="031122" +%s) - $(date --date="021020" +%s) )/(60*60*24) ))





                      share|improve this answer















                      The bash way - convert the dates into %y%m%d format and then you can do this straight from the command line:



                      echo $(( ($(date --date="031122" +%s) - $(date --date="021020" +%s) )/(60*60*24) ))






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jan 14 '14 at 19:47









                      Paul Bellora

                      45.4k15111161




                      45.4k15111161










                      answered Aug 4 '11 at 21:38









                      techjackertechjacker

                      91721011




                      91721011








                      • 9





                        This doesn't necessarily need the dates to be in %y%m%d format. E.g. gnu date will accept the %Y-%m-%d format the OP used. In general, ISO-8601 is a good choice (and the OP's format is one such format). Formats with 2 digit years are better avoided.

                        – mc0e
                        Jun 16 '15 at 11:52






                      • 2





                        For the difference from today, one may like to use days_diff=$(( (`date -d $B +%s` - `date -d "00:00" +%s`) / (24*3600) )). note that $days_diff will be an integer (i.e. no decimals)

                        – Julien
                        Jan 7 '16 at 10:41











                      • This is dependent on the variant of date installed. It works for GNU date. It doesn't work with POSIX date. This probably isn't a problem for most readers, but it's worth noting.

                        – mc0e
                        Mar 1 '18 at 15:01











                      • If you really want POSIX portability, check this: unix.stackexchange.com/a/7220/43835

                        – mc0e
                        Mar 1 '18 at 15:05
















                      • 9





                        This doesn't necessarily need the dates to be in %y%m%d format. E.g. gnu date will accept the %Y-%m-%d format the OP used. In general, ISO-8601 is a good choice (and the OP's format is one such format). Formats with 2 digit years are better avoided.

                        – mc0e
                        Jun 16 '15 at 11:52






                      • 2





                        For the difference from today, one may like to use days_diff=$(( (`date -d $B +%s` - `date -d "00:00" +%s`) / (24*3600) )). note that $days_diff will be an integer (i.e. no decimals)

                        – Julien
                        Jan 7 '16 at 10:41











                      • This is dependent on the variant of date installed. It works for GNU date. It doesn't work with POSIX date. This probably isn't a problem for most readers, but it's worth noting.

                        – mc0e
                        Mar 1 '18 at 15:01











                      • If you really want POSIX portability, check this: unix.stackexchange.com/a/7220/43835

                        – mc0e
                        Mar 1 '18 at 15:05










                      9




                      9





                      This doesn't necessarily need the dates to be in %y%m%d format. E.g. gnu date will accept the %Y-%m-%d format the OP used. In general, ISO-8601 is a good choice (and the OP's format is one such format). Formats with 2 digit years are better avoided.

                      – mc0e
                      Jun 16 '15 at 11:52





                      This doesn't necessarily need the dates to be in %y%m%d format. E.g. gnu date will accept the %Y-%m-%d format the OP used. In general, ISO-8601 is a good choice (and the OP's format is one such format). Formats with 2 digit years are better avoided.

                      – mc0e
                      Jun 16 '15 at 11:52




                      2




                      2





                      For the difference from today, one may like to use days_diff=$(( (`date -d $B +%s` - `date -d "00:00" +%s`) / (24*3600) )). note that $days_diff will be an integer (i.e. no decimals)

                      – Julien
                      Jan 7 '16 at 10:41





                      For the difference from today, one may like to use days_diff=$(( (`date -d $B +%s` - `date -d "00:00" +%s`) / (24*3600) )). note that $days_diff will be an integer (i.e. no decimals)

                      – Julien
                      Jan 7 '16 at 10:41













                      This is dependent on the variant of date installed. It works for GNU date. It doesn't work with POSIX date. This probably isn't a problem for most readers, but it's worth noting.

                      – mc0e
                      Mar 1 '18 at 15:01





                      This is dependent on the variant of date installed. It works for GNU date. It doesn't work with POSIX date. This probably isn't a problem for most readers, but it's worth noting.

                      – mc0e
                      Mar 1 '18 at 15:01













                      If you really want POSIX portability, check this: unix.stackexchange.com/a/7220/43835

                      – mc0e
                      Mar 1 '18 at 15:05







                      If you really want POSIX portability, check this: unix.stackexchange.com/a/7220/43835

                      – mc0e
                      Mar 1 '18 at 15:05













                      14














                      And in python



                      $python -c "from datetime import date; print (date(2003,11,22)-date(2002,10,20)).days"
                      398





                      share|improve this answer



















                      • 2





                        +1 This is the most portable way.

                        – mouviciel
                        Oct 11 '13 at 8:03











                      • @mouviciel not really. Python is not always present.

                        – mc0e
                        Jun 16 '15 at 11:57











                      • @mc0e in that context, nothing is always present

                        – Anubis
                        Feb 28 '18 at 12:53








                      • 1





                        @Anubis the OP specified tags as bash and shell, so I think we can assume that we're talking about a *nix system. Within such systems, echo and date are reliably present, but python is not.

                        – mc0e
                        Mar 1 '18 at 14:53













                      • @mc0e yeah that makes sense. Even-though python2 is available in most *nix systems, when it comes to low-end devices (embedded etc..) we will have to survive only with primary tools.

                        – Anubis
                        Mar 2 '18 at 10:06
















                      14














                      And in python



                      $python -c "from datetime import date; print (date(2003,11,22)-date(2002,10,20)).days"
                      398





                      share|improve this answer



















                      • 2





                        +1 This is the most portable way.

                        – mouviciel
                        Oct 11 '13 at 8:03











                      • @mouviciel not really. Python is not always present.

                        – mc0e
                        Jun 16 '15 at 11:57











                      • @mc0e in that context, nothing is always present

                        – Anubis
                        Feb 28 '18 at 12:53








                      • 1





                        @Anubis the OP specified tags as bash and shell, so I think we can assume that we're talking about a *nix system. Within such systems, echo and date are reliably present, but python is not.

                        – mc0e
                        Mar 1 '18 at 14:53













                      • @mc0e yeah that makes sense. Even-though python2 is available in most *nix systems, when it comes to low-end devices (embedded etc..) we will have to survive only with primary tools.

                        – Anubis
                        Mar 2 '18 at 10:06














                      14












                      14








                      14







                      And in python



                      $python -c "from datetime import date; print (date(2003,11,22)-date(2002,10,20)).days"
                      398





                      share|improve this answer













                      And in python



                      $python -c "from datetime import date; print (date(2003,11,22)-date(2002,10,20)).days"
                      398






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 18 '11 at 8:10









                      Fred LaurentFred Laurent

                      6861812




                      6861812








                      • 2





                        +1 This is the most portable way.

                        – mouviciel
                        Oct 11 '13 at 8:03











                      • @mouviciel not really. Python is not always present.

                        – mc0e
                        Jun 16 '15 at 11:57











                      • @mc0e in that context, nothing is always present

                        – Anubis
                        Feb 28 '18 at 12:53








                      • 1





                        @Anubis the OP specified tags as bash and shell, so I think we can assume that we're talking about a *nix system. Within such systems, echo and date are reliably present, but python is not.

                        – mc0e
                        Mar 1 '18 at 14:53













                      • @mc0e yeah that makes sense. Even-though python2 is available in most *nix systems, when it comes to low-end devices (embedded etc..) we will have to survive only with primary tools.

                        – Anubis
                        Mar 2 '18 at 10:06














                      • 2





                        +1 This is the most portable way.

                        – mouviciel
                        Oct 11 '13 at 8:03











                      • @mouviciel not really. Python is not always present.

                        – mc0e
                        Jun 16 '15 at 11:57











                      • @mc0e in that context, nothing is always present

                        – Anubis
                        Feb 28 '18 at 12:53








                      • 1





                        @Anubis the OP specified tags as bash and shell, so I think we can assume that we're talking about a *nix system. Within such systems, echo and date are reliably present, but python is not.

                        – mc0e
                        Mar 1 '18 at 14:53













                      • @mc0e yeah that makes sense. Even-though python2 is available in most *nix systems, when it comes to low-end devices (embedded etc..) we will have to survive only with primary tools.

                        – Anubis
                        Mar 2 '18 at 10:06








                      2




                      2





                      +1 This is the most portable way.

                      – mouviciel
                      Oct 11 '13 at 8:03





                      +1 This is the most portable way.

                      – mouviciel
                      Oct 11 '13 at 8:03













                      @mouviciel not really. Python is not always present.

                      – mc0e
                      Jun 16 '15 at 11:57





                      @mouviciel not really. Python is not always present.

                      – mc0e
                      Jun 16 '15 at 11:57













                      @mc0e in that context, nothing is always present

                      – Anubis
                      Feb 28 '18 at 12:53







                      @mc0e in that context, nothing is always present

                      – Anubis
                      Feb 28 '18 at 12:53






                      1




                      1





                      @Anubis the OP specified tags as bash and shell, so I think we can assume that we're talking about a *nix system. Within such systems, echo and date are reliably present, but python is not.

                      – mc0e
                      Mar 1 '18 at 14:53







                      @Anubis the OP specified tags as bash and shell, so I think we can assume that we're talking about a *nix system. Within such systems, echo and date are reliably present, but python is not.

                      – mc0e
                      Mar 1 '18 at 14:53















                      @mc0e yeah that makes sense. Even-though python2 is available in most *nix systems, when it comes to low-end devices (embedded etc..) we will have to survive only with primary tools.

                      – Anubis
                      Mar 2 '18 at 10:06





                      @mc0e yeah that makes sense. Even-though python2 is available in most *nix systems, when it comes to low-end devices (embedded etc..) we will have to survive only with primary tools.

                      – Anubis
                      Mar 2 '18 at 10:06











                      14














                      Watch out! Many of the bash solutions here are broken for date ranges which span the date when daylight savings time begins (where applicable). This is because the $(( math )) construct does a 'floor'/truncation operation on the resulting value, returning only the whole number. Let me illustrate:



                      DST started March 8th this year in the US, so let's use a date range spanning that:



                      start_ts=$(date -d "2015-03-05" '+%s')
                      end_ts=$(date -d "2015-03-11" '+%s')


                      Let's see what we get with the double parentheses:



                      echo $(( ( end_ts - start_ts )/(60*60*24) ))


                      Returns '5'.



                      Doing this using 'bc' with more accuracy gives us a different result:



                      echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc


                      Returns '5.95' - the missing 0.05 being the lost hour from the DST switchover.



                      So how should this be done correctly?

                      I would suggest using this instead:



                      printf "%.0f" $(echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc)


                      Here, the 'printf' rounds the more accurate result calculated by 'bc', giving us the correct date range of '6'.



                      Edit: highlighting the answer in a comment from @hank-schultz below, which I have been using lately:



                      date_diff=$(( ($(date -d "2015-03-11 UTC" +%s) - $(date -d "2015-03-05 UTC" +%s) )/(60*60*24) ))


                      This should also be leap second safe as long as you always subtract the earlier date from the later one, since leap seconds will only ever add to the difference - truncation effectively rounds down to the correct result.






                      share|improve this answer





















                      • 3





                        If instead, you specify the timezone for both the start and the end (and make sure they are the same), then you also no longer have this problem, like so: echo $(( ($(date --date="2015-03-11 UTC" +%s) - $(date --date="2015-03-05 UTC" +%s) )/(60*60*24) )), which returns 6, instead of 5.

                        – Hank Schultz
                        Jun 23 '15 at 20:40








                      • 1





                        Ah, one of the answerers thought about the inaccuracies of the basic solution repeated by others in variants. Thumbs up! How about leap seconds? It is leap-second-safe? There are precedents of software returning off-by-one-day result if run at certain times, ref problems associated with the leap second.

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:29











                      • Woops, the "wrong" computation you give as example correctly returns 6 here (Ubuntu 15.04 AMD64, GNU date version 8.23). Perhaps your example is timezone-dependant? My timezone is "Europe/Paris".

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:34











                      • Same good result for the "wrong" computation with GNU date 2.0 on MSYS, same timezone.

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:35






                      • 1





                        @StéphaneGourichon, your timezone's daylight savings change looks to have happened on March 29, 2015 - so try a date range which includes that.

                        – evan_b
                        Dec 4 '15 at 22:22
















                      14














                      Watch out! Many of the bash solutions here are broken for date ranges which span the date when daylight savings time begins (where applicable). This is because the $(( math )) construct does a 'floor'/truncation operation on the resulting value, returning only the whole number. Let me illustrate:



                      DST started March 8th this year in the US, so let's use a date range spanning that:



                      start_ts=$(date -d "2015-03-05" '+%s')
                      end_ts=$(date -d "2015-03-11" '+%s')


                      Let's see what we get with the double parentheses:



                      echo $(( ( end_ts - start_ts )/(60*60*24) ))


                      Returns '5'.



                      Doing this using 'bc' with more accuracy gives us a different result:



                      echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc


                      Returns '5.95' - the missing 0.05 being the lost hour from the DST switchover.



                      So how should this be done correctly?

                      I would suggest using this instead:



                      printf "%.0f" $(echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc)


                      Here, the 'printf' rounds the more accurate result calculated by 'bc', giving us the correct date range of '6'.



                      Edit: highlighting the answer in a comment from @hank-schultz below, which I have been using lately:



                      date_diff=$(( ($(date -d "2015-03-11 UTC" +%s) - $(date -d "2015-03-05 UTC" +%s) )/(60*60*24) ))


                      This should also be leap second safe as long as you always subtract the earlier date from the later one, since leap seconds will only ever add to the difference - truncation effectively rounds down to the correct result.






                      share|improve this answer





















                      • 3





                        If instead, you specify the timezone for both the start and the end (and make sure they are the same), then you also no longer have this problem, like so: echo $(( ($(date --date="2015-03-11 UTC" +%s) - $(date --date="2015-03-05 UTC" +%s) )/(60*60*24) )), which returns 6, instead of 5.

                        – Hank Schultz
                        Jun 23 '15 at 20:40








                      • 1





                        Ah, one of the answerers thought about the inaccuracies of the basic solution repeated by others in variants. Thumbs up! How about leap seconds? It is leap-second-safe? There are precedents of software returning off-by-one-day result if run at certain times, ref problems associated with the leap second.

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:29











                      • Woops, the "wrong" computation you give as example correctly returns 6 here (Ubuntu 15.04 AMD64, GNU date version 8.23). Perhaps your example is timezone-dependant? My timezone is "Europe/Paris".

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:34











                      • Same good result for the "wrong" computation with GNU date 2.0 on MSYS, same timezone.

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:35






                      • 1





                        @StéphaneGourichon, your timezone's daylight savings change looks to have happened on March 29, 2015 - so try a date range which includes that.

                        – evan_b
                        Dec 4 '15 at 22:22














                      14












                      14








                      14







                      Watch out! Many of the bash solutions here are broken for date ranges which span the date when daylight savings time begins (where applicable). This is because the $(( math )) construct does a 'floor'/truncation operation on the resulting value, returning only the whole number. Let me illustrate:



                      DST started March 8th this year in the US, so let's use a date range spanning that:



                      start_ts=$(date -d "2015-03-05" '+%s')
                      end_ts=$(date -d "2015-03-11" '+%s')


                      Let's see what we get with the double parentheses:



                      echo $(( ( end_ts - start_ts )/(60*60*24) ))


                      Returns '5'.



                      Doing this using 'bc' with more accuracy gives us a different result:



                      echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc


                      Returns '5.95' - the missing 0.05 being the lost hour from the DST switchover.



                      So how should this be done correctly?

                      I would suggest using this instead:



                      printf "%.0f" $(echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc)


                      Here, the 'printf' rounds the more accurate result calculated by 'bc', giving us the correct date range of '6'.



                      Edit: highlighting the answer in a comment from @hank-schultz below, which I have been using lately:



                      date_diff=$(( ($(date -d "2015-03-11 UTC" +%s) - $(date -d "2015-03-05 UTC" +%s) )/(60*60*24) ))


                      This should also be leap second safe as long as you always subtract the earlier date from the later one, since leap seconds will only ever add to the difference - truncation effectively rounds down to the correct result.






                      share|improve this answer















                      Watch out! Many of the bash solutions here are broken for date ranges which span the date when daylight savings time begins (where applicable). This is because the $(( math )) construct does a 'floor'/truncation operation on the resulting value, returning only the whole number. Let me illustrate:



                      DST started March 8th this year in the US, so let's use a date range spanning that:



                      start_ts=$(date -d "2015-03-05" '+%s')
                      end_ts=$(date -d "2015-03-11" '+%s')


                      Let's see what we get with the double parentheses:



                      echo $(( ( end_ts - start_ts )/(60*60*24) ))


                      Returns '5'.



                      Doing this using 'bc' with more accuracy gives us a different result:



                      echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc


                      Returns '5.95' - the missing 0.05 being the lost hour from the DST switchover.



                      So how should this be done correctly?

                      I would suggest using this instead:



                      printf "%.0f" $(echo "scale=2; ( $end_ts - $start_ts )/(60*60*24)" | bc)


                      Here, the 'printf' rounds the more accurate result calculated by 'bc', giving us the correct date range of '6'.



                      Edit: highlighting the answer in a comment from @hank-schultz below, which I have been using lately:



                      date_diff=$(( ($(date -d "2015-03-11 UTC" +%s) - $(date -d "2015-03-05 UTC" +%s) )/(60*60*24) ))


                      This should also be leap second safe as long as you always subtract the earlier date from the later one, since leap seconds will only ever add to the difference - truncation effectively rounds down to the correct result.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Dec 27 '17 at 22:22

























                      answered Mar 12 '15 at 19:53









                      evan_bevan_b

                      311212




                      311212








                      • 3





                        If instead, you specify the timezone for both the start and the end (and make sure they are the same), then you also no longer have this problem, like so: echo $(( ($(date --date="2015-03-11 UTC" +%s) - $(date --date="2015-03-05 UTC" +%s) )/(60*60*24) )), which returns 6, instead of 5.

                        – Hank Schultz
                        Jun 23 '15 at 20:40








                      • 1





                        Ah, one of the answerers thought about the inaccuracies of the basic solution repeated by others in variants. Thumbs up! How about leap seconds? It is leap-second-safe? There are precedents of software returning off-by-one-day result if run at certain times, ref problems associated with the leap second.

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:29











                      • Woops, the "wrong" computation you give as example correctly returns 6 here (Ubuntu 15.04 AMD64, GNU date version 8.23). Perhaps your example is timezone-dependant? My timezone is "Europe/Paris".

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:34











                      • Same good result for the "wrong" computation with GNU date 2.0 on MSYS, same timezone.

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:35






                      • 1





                        @StéphaneGourichon, your timezone's daylight savings change looks to have happened on March 29, 2015 - so try a date range which includes that.

                        – evan_b
                        Dec 4 '15 at 22:22














                      • 3





                        If instead, you specify the timezone for both the start and the end (and make sure they are the same), then you also no longer have this problem, like so: echo $(( ($(date --date="2015-03-11 UTC" +%s) - $(date --date="2015-03-05 UTC" +%s) )/(60*60*24) )), which returns 6, instead of 5.

                        – Hank Schultz
                        Jun 23 '15 at 20:40








                      • 1





                        Ah, one of the answerers thought about the inaccuracies of the basic solution repeated by others in variants. Thumbs up! How about leap seconds? It is leap-second-safe? There are precedents of software returning off-by-one-day result if run at certain times, ref problems associated with the leap second.

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:29











                      • Woops, the "wrong" computation you give as example correctly returns 6 here (Ubuntu 15.04 AMD64, GNU date version 8.23). Perhaps your example is timezone-dependant? My timezone is "Europe/Paris".

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:34











                      • Same good result for the "wrong" computation with GNU date 2.0 on MSYS, same timezone.

                        – Stéphane Gourichon
                        Nov 20 '15 at 12:35






                      • 1





                        @StéphaneGourichon, your timezone's daylight savings change looks to have happened on March 29, 2015 - so try a date range which includes that.

                        – evan_b
                        Dec 4 '15 at 22:22








                      3




                      3





                      If instead, you specify the timezone for both the start and the end (and make sure they are the same), then you also no longer have this problem, like so: echo $(( ($(date --date="2015-03-11 UTC" +%s) - $(date --date="2015-03-05 UTC" +%s) )/(60*60*24) )), which returns 6, instead of 5.

                      – Hank Schultz
                      Jun 23 '15 at 20:40







                      If instead, you specify the timezone for both the start and the end (and make sure they are the same), then you also no longer have this problem, like so: echo $(( ($(date --date="2015-03-11 UTC" +%s) - $(date --date="2015-03-05 UTC" +%s) )/(60*60*24) )), which returns 6, instead of 5.

                      – Hank Schultz
                      Jun 23 '15 at 20:40






                      1




                      1





                      Ah, one of the answerers thought about the inaccuracies of the basic solution repeated by others in variants. Thumbs up! How about leap seconds? It is leap-second-safe? There are precedents of software returning off-by-one-day result if run at certain times, ref problems associated with the leap second.

                      – Stéphane Gourichon
                      Nov 20 '15 at 12:29





                      Ah, one of the answerers thought about the inaccuracies of the basic solution repeated by others in variants. Thumbs up! How about leap seconds? It is leap-second-safe? There are precedents of software returning off-by-one-day result if run at certain times, ref problems associated with the leap second.

                      – Stéphane Gourichon
                      Nov 20 '15 at 12:29













                      Woops, the "wrong" computation you give as example correctly returns 6 here (Ubuntu 15.04 AMD64, GNU date version 8.23). Perhaps your example is timezone-dependant? My timezone is "Europe/Paris".

                      – Stéphane Gourichon
                      Nov 20 '15 at 12:34





                      Woops, the "wrong" computation you give as example correctly returns 6 here (Ubuntu 15.04 AMD64, GNU date version 8.23). Perhaps your example is timezone-dependant? My timezone is "Europe/Paris".

                      – Stéphane Gourichon
                      Nov 20 '15 at 12:34













                      Same good result for the "wrong" computation with GNU date 2.0 on MSYS, same timezone.

                      – Stéphane Gourichon
                      Nov 20 '15 at 12:35





                      Same good result for the "wrong" computation with GNU date 2.0 on MSYS, same timezone.

                      – Stéphane Gourichon
                      Nov 20 '15 at 12:35




                      1




                      1





                      @StéphaneGourichon, your timezone's daylight savings change looks to have happened on March 29, 2015 - so try a date range which includes that.

                      – evan_b
                      Dec 4 '15 at 22:22





                      @StéphaneGourichon, your timezone's daylight savings change looks to have happened on March 29, 2015 - so try a date range which includes that.

                      – evan_b
                      Dec 4 '15 at 22:22











                      6














                      Here's the MAC OS X version for your convenience.



                      $ A="2002-20-10"; B="2003-22-11";
                      $ echo $(((`date -jf %Y-%d-%m $B +%s` - `date -jf %Y-%d-%m $A +%s`)/86400))


                      nJoy!






                      share|improve this answer





















                      • 1





                        -bash: ( - )/86400: syntax error: operand expected (error token is ")/86400")

                        – cavalcade
                        Nov 1 '16 at 0:56






                      • 1





                        @cavalcade - that is because you haven't done A="2002-20-10"; B="2003-22-11"

                        – RAM237
                        Jul 5 '17 at 13:43













                      • Thanks, despite it works for this particular case, I would suggest using echo $(((`date -jf "%Y-%d-%m" "$B" +%s` - `date -jf "%Y-%d-%m" "$A" +%s`)/86400)), i.e. wrapping both formats and variables into double quotes, otherwise may fail on different date format (e.g. %b %d, %Y/Jul 5, 2017)

                        – RAM237
                        Jul 5 '17 at 13:46













                      • @RAM237 Thats what I get for not paying attention headsmack Well spotted, thanks

                        – cavalcade
                        May 16 '18 at 12:54
















                      6














                      Here's the MAC OS X version for your convenience.



                      $ A="2002-20-10"; B="2003-22-11";
                      $ echo $(((`date -jf %Y-%d-%m $B +%s` - `date -jf %Y-%d-%m $A +%s`)/86400))


                      nJoy!






                      share|improve this answer





















                      • 1





                        -bash: ( - )/86400: syntax error: operand expected (error token is ")/86400")

                        – cavalcade
                        Nov 1 '16 at 0:56






                      • 1





                        @cavalcade - that is because you haven't done A="2002-20-10"; B="2003-22-11"

                        – RAM237
                        Jul 5 '17 at 13:43













                      • Thanks, despite it works for this particular case, I would suggest using echo $(((`date -jf "%Y-%d-%m" "$B" +%s` - `date -jf "%Y-%d-%m" "$A" +%s`)/86400)), i.e. wrapping both formats and variables into double quotes, otherwise may fail on different date format (e.g. %b %d, %Y/Jul 5, 2017)

                        – RAM237
                        Jul 5 '17 at 13:46













                      • @RAM237 Thats what I get for not paying attention headsmack Well spotted, thanks

                        – cavalcade
                        May 16 '18 at 12:54














                      6












                      6








                      6







                      Here's the MAC OS X version for your convenience.



                      $ A="2002-20-10"; B="2003-22-11";
                      $ echo $(((`date -jf %Y-%d-%m $B +%s` - `date -jf %Y-%d-%m $A +%s`)/86400))


                      nJoy!






                      share|improve this answer















                      Here's the MAC OS X version for your convenience.



                      $ A="2002-20-10"; B="2003-22-11";
                      $ echo $(((`date -jf %Y-%d-%m $B +%s` - `date -jf %Y-%d-%m $A +%s`)/86400))


                      nJoy!







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited May 30 '18 at 2:45

























                      answered Dec 27 '12 at 13:54









                      nickl-nickl-

                      5,24822935




                      5,24822935








                      • 1





                        -bash: ( - )/86400: syntax error: operand expected (error token is ")/86400")

                        – cavalcade
                        Nov 1 '16 at 0:56






                      • 1





                        @cavalcade - that is because you haven't done A="2002-20-10"; B="2003-22-11"

                        – RAM237
                        Jul 5 '17 at 13:43













                      • Thanks, despite it works for this particular case, I would suggest using echo $(((`date -jf "%Y-%d-%m" "$B" +%s` - `date -jf "%Y-%d-%m" "$A" +%s`)/86400)), i.e. wrapping both formats and variables into double quotes, otherwise may fail on different date format (e.g. %b %d, %Y/Jul 5, 2017)

                        – RAM237
                        Jul 5 '17 at 13:46













                      • @RAM237 Thats what I get for not paying attention headsmack Well spotted, thanks

                        – cavalcade
                        May 16 '18 at 12:54














                      • 1





                        -bash: ( - )/86400: syntax error: operand expected (error token is ")/86400")

                        – cavalcade
                        Nov 1 '16 at 0:56






                      • 1





                        @cavalcade - that is because you haven't done A="2002-20-10"; B="2003-22-11"

                        – RAM237
                        Jul 5 '17 at 13:43













                      • Thanks, despite it works for this particular case, I would suggest using echo $(((`date -jf "%Y-%d-%m" "$B" +%s` - `date -jf "%Y-%d-%m" "$A" +%s`)/86400)), i.e. wrapping both formats and variables into double quotes, otherwise may fail on different date format (e.g. %b %d, %Y/Jul 5, 2017)

                        – RAM237
                        Jul 5 '17 at 13:46













                      • @RAM237 Thats what I get for not paying attention headsmack Well spotted, thanks

                        – cavalcade
                        May 16 '18 at 12:54








                      1




                      1





                      -bash: ( - )/86400: syntax error: operand expected (error token is ")/86400")

                      – cavalcade
                      Nov 1 '16 at 0:56





                      -bash: ( - )/86400: syntax error: operand expected (error token is ")/86400")

                      – cavalcade
                      Nov 1 '16 at 0:56




                      1




                      1





                      @cavalcade - that is because you haven't done A="2002-20-10"; B="2003-22-11"

                      – RAM237
                      Jul 5 '17 at 13:43







                      @cavalcade - that is because you haven't done A="2002-20-10"; B="2003-22-11"

                      – RAM237
                      Jul 5 '17 at 13:43















                      Thanks, despite it works for this particular case, I would suggest using echo $(((`date -jf "%Y-%d-%m" "$B" +%s` - `date -jf "%Y-%d-%m" "$A" +%s`)/86400)), i.e. wrapping both formats and variables into double quotes, otherwise may fail on different date format (e.g. %b %d, %Y/Jul 5, 2017)

                      – RAM237
                      Jul 5 '17 at 13:46







                      Thanks, despite it works for this particular case, I would suggest using echo $(((`date -jf "%Y-%d-%m" "$B" +%s` - `date -jf "%Y-%d-%m" "$A" +%s`)/86400)), i.e. wrapping both formats and variables into double quotes, otherwise may fail on different date format (e.g. %b %d, %Y/Jul 5, 2017)

                      – RAM237
                      Jul 5 '17 at 13:46















                      @RAM237 Thats what I get for not paying attention headsmack Well spotted, thanks

                      – cavalcade
                      May 16 '18 at 12:54





                      @RAM237 Thats what I get for not paying attention headsmack Well spotted, thanks

                      – cavalcade
                      May 16 '18 at 12:54











                      4














                      If the option -d works in your system, here's another way to do it. There is a caveat that it wouldn't account for leap years since I've considered 365 days per year.



                      date1yrs=`date -d "20100209" +%Y`
                      date1days=`date -d "20100209" +%j`
                      date2yrs=`date +%Y`
                      date2days=`date +%j`
                      diffyr=`expr $date2yrs - $date1yrs`
                      diffyr2days=`expr $diffyr * 365`
                      diffdays=`expr $date2days - $date1days`
                      echo `expr $diffyr2days + $diffdays`





                      share|improve this answer




























                        4














                        If the option -d works in your system, here's another way to do it. There is a caveat that it wouldn't account for leap years since I've considered 365 days per year.



                        date1yrs=`date -d "20100209" +%Y`
                        date1days=`date -d "20100209" +%j`
                        date2yrs=`date +%Y`
                        date2days=`date +%j`
                        diffyr=`expr $date2yrs - $date1yrs`
                        diffyr2days=`expr $diffyr * 365`
                        diffdays=`expr $date2days - $date1days`
                        echo `expr $diffyr2days + $diffdays`





                        share|improve this answer


























                          4












                          4








                          4







                          If the option -d works in your system, here's another way to do it. There is a caveat that it wouldn't account for leap years since I've considered 365 days per year.



                          date1yrs=`date -d "20100209" +%Y`
                          date1days=`date -d "20100209" +%j`
                          date2yrs=`date +%Y`
                          date2days=`date +%j`
                          diffyr=`expr $date2yrs - $date1yrs`
                          diffyr2days=`expr $diffyr * 365`
                          diffdays=`expr $date2days - $date1days`
                          echo `expr $diffyr2days + $diffdays`





                          share|improve this answer













                          If the option -d works in your system, here's another way to do it. There is a caveat that it wouldn't account for leap years since I've considered 365 days per year.



                          date1yrs=`date -d "20100209" +%Y`
                          date1days=`date -d "20100209" +%j`
                          date2yrs=`date +%Y`
                          date2days=`date +%j`
                          diffyr=`expr $date2yrs - $date1yrs`
                          diffyr2days=`expr $diffyr * 365`
                          diffdays=`expr $date2days - $date1days`
                          echo `expr $diffyr2days + $diffdays`






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Feb 9 '11 at 17:09









                          RuchiRuchi

                          521211




                          521211























                              4














                              Even if you don't have GNU date, you'll probably have Perl installed:



                              use Time::Local;
                              sub to_epoch {
                              my ($t) = @_;
                              my ($y, $d, $m) = ($t =~ /(d{4})-(d{2})-(d{2})/);
                              return timelocal(0, 0, 0, $d+0, $m-1, $y-1900);
                              }
                              sub diff_days {
                              my ($t1, $t2) = @_;
                              return (abs(to_epoch($t2) - to_epoch($t1))) / 86400;
                              }
                              print diff_days("2002-20-10", "2003-22-11"), "n";


                              This returns 398.041666666667 -- 398 days and one hour due to daylight savings.





                              The question came back up on my feed. Here's a more concise method using a Perl bundled module



                              days=$(perl -MDateTime -le '
                              sub parse_date {
                              @f = split /-/, shift;
                              return DateTime->new(year=>$f[0], month=>$f[2], day=>$f[1]);
                              }
                              print parse_date(shift)->delta_days(parse_date(shift))->in_units("days");
                              ' $A $B)
                              echo $days # => 398





                              share|improve this answer






























                                4














                                Even if you don't have GNU date, you'll probably have Perl installed:



                                use Time::Local;
                                sub to_epoch {
                                my ($t) = @_;
                                my ($y, $d, $m) = ($t =~ /(d{4})-(d{2})-(d{2})/);
                                return timelocal(0, 0, 0, $d+0, $m-1, $y-1900);
                                }
                                sub diff_days {
                                my ($t1, $t2) = @_;
                                return (abs(to_epoch($t2) - to_epoch($t1))) / 86400;
                                }
                                print diff_days("2002-20-10", "2003-22-11"), "n";


                                This returns 398.041666666667 -- 398 days and one hour due to daylight savings.





                                The question came back up on my feed. Here's a more concise method using a Perl bundled module



                                days=$(perl -MDateTime -le '
                                sub parse_date {
                                @f = split /-/, shift;
                                return DateTime->new(year=>$f[0], month=>$f[2], day=>$f[1]);
                                }
                                print parse_date(shift)->delta_days(parse_date(shift))->in_units("days");
                                ' $A $B)
                                echo $days # => 398





                                share|improve this answer




























                                  4












                                  4








                                  4







                                  Even if you don't have GNU date, you'll probably have Perl installed:



                                  use Time::Local;
                                  sub to_epoch {
                                  my ($t) = @_;
                                  my ($y, $d, $m) = ($t =~ /(d{4})-(d{2})-(d{2})/);
                                  return timelocal(0, 0, 0, $d+0, $m-1, $y-1900);
                                  }
                                  sub diff_days {
                                  my ($t1, $t2) = @_;
                                  return (abs(to_epoch($t2) - to_epoch($t1))) / 86400;
                                  }
                                  print diff_days("2002-20-10", "2003-22-11"), "n";


                                  This returns 398.041666666667 -- 398 days and one hour due to daylight savings.





                                  The question came back up on my feed. Here's a more concise method using a Perl bundled module



                                  days=$(perl -MDateTime -le '
                                  sub parse_date {
                                  @f = split /-/, shift;
                                  return DateTime->new(year=>$f[0], month=>$f[2], day=>$f[1]);
                                  }
                                  print parse_date(shift)->delta_days(parse_date(shift))->in_units("days");
                                  ' $A $B)
                                  echo $days # => 398





                                  share|improve this answer















                                  Even if you don't have GNU date, you'll probably have Perl installed:



                                  use Time::Local;
                                  sub to_epoch {
                                  my ($t) = @_;
                                  my ($y, $d, $m) = ($t =~ /(d{4})-(d{2})-(d{2})/);
                                  return timelocal(0, 0, 0, $d+0, $m-1, $y-1900);
                                  }
                                  sub diff_days {
                                  my ($t1, $t2) = @_;
                                  return (abs(to_epoch($t2) - to_epoch($t1))) / 86400;
                                  }
                                  print diff_days("2002-20-10", "2003-22-11"), "n";


                                  This returns 398.041666666667 -- 398 days and one hour due to daylight savings.





                                  The question came back up on my feed. Here's a more concise method using a Perl bundled module



                                  days=$(perl -MDateTime -le '
                                  sub parse_date {
                                  @f = split /-/, shift;
                                  return DateTime->new(year=>$f[0], month=>$f[2], day=>$f[1]);
                                  }
                                  print parse_date(shift)->delta_days(parse_date(shift))->in_units("days");
                                  ' $A $B)
                                  echo $days # => 398






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jun 18 '13 at 20:01

























                                  answered Feb 9 '11 at 17:51









                                  glenn jackmanglenn jackman

                                  166k26143237




                                  166k26143237























                                      2














                                      This works for me:



                                      A="2002-10-20"
                                      B="2003-11-22"
                                      echo $(( ($(date -d $B +%s) - $(date -d $A +%s)) / 86400 )) days


                                      Prints



                                      398 days


                                      What is happening?




                                      1. Provide valid time string in A and B

                                      2. Use date -d to handle time strings

                                      3. Use date %s to convert time strings to seconds since 1970 (unix epoche)

                                      4. Use bash parameter expansion to subtract seconds

                                      5. divide by seconds per day (86400=60*60*24) to get difference as days

                                      6. ! DST is not taken into account ! See this answer at unix.stackexchange!






                                      share|improve this answer






























                                        2














                                        This works for me:



                                        A="2002-10-20"
                                        B="2003-11-22"
                                        echo $(( ($(date -d $B +%s) - $(date -d $A +%s)) / 86400 )) days


                                        Prints



                                        398 days


                                        What is happening?




                                        1. Provide valid time string in A and B

                                        2. Use date -d to handle time strings

                                        3. Use date %s to convert time strings to seconds since 1970 (unix epoche)

                                        4. Use bash parameter expansion to subtract seconds

                                        5. divide by seconds per day (86400=60*60*24) to get difference as days

                                        6. ! DST is not taken into account ! See this answer at unix.stackexchange!






                                        share|improve this answer




























                                          2












                                          2








                                          2







                                          This works for me:



                                          A="2002-10-20"
                                          B="2003-11-22"
                                          echo $(( ($(date -d $B +%s) - $(date -d $A +%s)) / 86400 )) days


                                          Prints



                                          398 days


                                          What is happening?




                                          1. Provide valid time string in A and B

                                          2. Use date -d to handle time strings

                                          3. Use date %s to convert time strings to seconds since 1970 (unix epoche)

                                          4. Use bash parameter expansion to subtract seconds

                                          5. divide by seconds per day (86400=60*60*24) to get difference as days

                                          6. ! DST is not taken into account ! See this answer at unix.stackexchange!






                                          share|improve this answer















                                          This works for me:



                                          A="2002-10-20"
                                          B="2003-11-22"
                                          echo $(( ($(date -d $B +%s) - $(date -d $A +%s)) / 86400 )) days


                                          Prints



                                          398 days


                                          What is happening?




                                          1. Provide valid time string in A and B

                                          2. Use date -d to handle time strings

                                          3. Use date %s to convert time strings to seconds since 1970 (unix epoche)

                                          4. Use bash parameter expansion to subtract seconds

                                          5. divide by seconds per day (86400=60*60*24) to get difference as days

                                          6. ! DST is not taken into account ! See this answer at unix.stackexchange!







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited 17 hours ago

























                                          answered Apr 9 '18 at 7:57









                                          jschnassejschnasse

                                          1,9951125




                                          1,9951125























                                              1














                                              I'd submit another possible solution in Ruby. Looks like it's the be smallest and cleanest looking one so far:



                                              A=2003-12-11
                                              B=2002-10-10
                                              DIFF=$(ruby -rdate -e "puts Date.parse('$A') - Date.parse('$B')")
                                              echo $DIFF





                                              share|improve this answer



















                                              • 1





                                                He is looking for a way in bash.

                                                – Cojones
                                                Mar 7 '12 at 11:26






                                              • 2





                                                There is no portable way to do it in shell itself. All alternatives use particular external programs (i.e. GNU date or some scripting language) and I honestly think that Ruby is a good way to go here. This solution is very short and does not use any non-standard libraries or other dependencies. In fact, I think that there's a higher chance of having Ruby installed than one would have GNU date installed.

                                                – GreyCat
                                                Mar 8 '12 at 21:14
















                                              1














                                              I'd submit another possible solution in Ruby. Looks like it's the be smallest and cleanest looking one so far:



                                              A=2003-12-11
                                              B=2002-10-10
                                              DIFF=$(ruby -rdate -e "puts Date.parse('$A') - Date.parse('$B')")
                                              echo $DIFF





                                              share|improve this answer



















                                              • 1





                                                He is looking for a way in bash.

                                                – Cojones
                                                Mar 7 '12 at 11:26






                                              • 2





                                                There is no portable way to do it in shell itself. All alternatives use particular external programs (i.e. GNU date or some scripting language) and I honestly think that Ruby is a good way to go here. This solution is very short and does not use any non-standard libraries or other dependencies. In fact, I think that there's a higher chance of having Ruby installed than one would have GNU date installed.

                                                – GreyCat
                                                Mar 8 '12 at 21:14














                                              1












                                              1








                                              1







                                              I'd submit another possible solution in Ruby. Looks like it's the be smallest and cleanest looking one so far:



                                              A=2003-12-11
                                              B=2002-10-10
                                              DIFF=$(ruby -rdate -e "puts Date.parse('$A') - Date.parse('$B')")
                                              echo $DIFF





                                              share|improve this answer













                                              I'd submit another possible solution in Ruby. Looks like it's the be smallest and cleanest looking one so far:



                                              A=2003-12-11
                                              B=2002-10-10
                                              DIFF=$(ruby -rdate -e "puts Date.parse('$A') - Date.parse('$B')")
                                              echo $DIFF






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Feb 10 '11 at 15:52









                                              GreyCatGreyCat

                                              7,892145997




                                              7,892145997








                                              • 1





                                                He is looking for a way in bash.

                                                – Cojones
                                                Mar 7 '12 at 11:26






                                              • 2





                                                There is no portable way to do it in shell itself. All alternatives use particular external programs (i.e. GNU date or some scripting language) and I honestly think that Ruby is a good way to go here. This solution is very short and does not use any non-standard libraries or other dependencies. In fact, I think that there's a higher chance of having Ruby installed than one would have GNU date installed.

                                                – GreyCat
                                                Mar 8 '12 at 21:14














                                              • 1





                                                He is looking for a way in bash.

                                                – Cojones
                                                Mar 7 '12 at 11:26






                                              • 2





                                                There is no portable way to do it in shell itself. All alternatives use particular external programs (i.e. GNU date or some scripting language) and I honestly think that Ruby is a good way to go here. This solution is very short and does not use any non-standard libraries or other dependencies. In fact, I think that there's a higher chance of having Ruby installed than one would have GNU date installed.

                                                – GreyCat
                                                Mar 8 '12 at 21:14








                                              1




                                              1





                                              He is looking for a way in bash.

                                              – Cojones
                                              Mar 7 '12 at 11:26





                                              He is looking for a way in bash.

                                              – Cojones
                                              Mar 7 '12 at 11:26




                                              2




                                              2





                                              There is no portable way to do it in shell itself. All alternatives use particular external programs (i.e. GNU date or some scripting language) and I honestly think that Ruby is a good way to go here. This solution is very short and does not use any non-standard libraries or other dependencies. In fact, I think that there's a higher chance of having Ruby installed than one would have GNU date installed.

                                              – GreyCat
                                              Mar 8 '12 at 21:14





                                              There is no portable way to do it in shell itself. All alternatives use particular external programs (i.e. GNU date or some scripting language) and I honestly think that Ruby is a good way to go here. This solution is very short and does not use any non-standard libraries or other dependencies. In fact, I think that there's a higher chance of having Ruby installed than one would have GNU date installed.

                                              – GreyCat
                                              Mar 8 '12 at 21:14











                                              1














                                              on unix you should have GNU dates installed. you do not need to deviate from bash. here is the strung out solution considering days, just to show the steps. it can be simplified and extended to full dates.



                                              DATE=$(echo `date`)
                                              DATENOW=$(echo `date -d "$DATE" +%j`)
                                              DATECOMING=$(echo `date -d "20131220" +%j`)
                                              THEDAY=$(echo `expr $DATECOMING - $DATENOW`)

                                              echo $THEDAY





                                              share|improve this answer






























                                                1














                                                on unix you should have GNU dates installed. you do not need to deviate from bash. here is the strung out solution considering days, just to show the steps. it can be simplified and extended to full dates.



                                                DATE=$(echo `date`)
                                                DATENOW=$(echo `date -d "$DATE" +%j`)
                                                DATECOMING=$(echo `date -d "20131220" +%j`)
                                                THEDAY=$(echo `expr $DATECOMING - $DATENOW`)

                                                echo $THEDAY





                                                share|improve this answer




























                                                  1












                                                  1








                                                  1







                                                  on unix you should have GNU dates installed. you do not need to deviate from bash. here is the strung out solution considering days, just to show the steps. it can be simplified and extended to full dates.



                                                  DATE=$(echo `date`)
                                                  DATENOW=$(echo `date -d "$DATE" +%j`)
                                                  DATECOMING=$(echo `date -d "20131220" +%j`)
                                                  THEDAY=$(echo `expr $DATECOMING - $DATENOW`)

                                                  echo $THEDAY





                                                  share|improve this answer















                                                  on unix you should have GNU dates installed. you do not need to deviate from bash. here is the strung out solution considering days, just to show the steps. it can be simplified and extended to full dates.



                                                  DATE=$(echo `date`)
                                                  DATENOW=$(echo `date -d "$DATE" +%j`)
                                                  DATECOMING=$(echo `date -d "20131220" +%j`)
                                                  THEDAY=$(echo `expr $DATECOMING - $DATENOW`)

                                                  echo $THEDAY






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Dec 1 '13 at 0:41

























                                                  answered Nov 30 '13 at 4:11









                                                  mattymikmattymik

                                                  113




                                                  113























                                                      0














                                                      Give this a try:



                                                      perl -e 'use Date::Calc qw(Delta_Days); printf "%dn", Delta_Days(2002,10,20,2003,11,22);'





                                                      share|improve this answer




























                                                        0














                                                        Give this a try:



                                                        perl -e 'use Date::Calc qw(Delta_Days); printf "%dn", Delta_Days(2002,10,20,2003,11,22);'





                                                        share|improve this answer


























                                                          0












                                                          0








                                                          0







                                                          Give this a try:



                                                          perl -e 'use Date::Calc qw(Delta_Days); printf "%dn", Delta_Days(2002,10,20,2003,11,22);'





                                                          share|improve this answer













                                                          Give this a try:



                                                          perl -e 'use Date::Calc qw(Delta_Days); printf "%dn", Delta_Days(2002,10,20,2003,11,22);'






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Feb 9 '11 at 18:00









                                                          Dennis WilliamsonDennis Williamson

                                                          238k63307372




                                                          238k63307372























                                                              0














                                                              Another Python version:



                                                              python -c "from datetime import date; print date(2003, 11, 22).toordinal() - date(2002, 10, 20).toordinal()"





                                                              share|improve this answer




























                                                                0














                                                                Another Python version:



                                                                python -c "from datetime import date; print date(2003, 11, 22).toordinal() - date(2002, 10, 20).toordinal()"





                                                                share|improve this answer


























                                                                  0












                                                                  0








                                                                  0







                                                                  Another Python version:



                                                                  python -c "from datetime import date; print date(2003, 11, 22).toordinal() - date(2002, 10, 20).toordinal()"





                                                                  share|improve this answer













                                                                  Another Python version:



                                                                  python -c "from datetime import date; print date(2003, 11, 22).toordinal() - date(2002, 10, 20).toordinal()"






                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Dec 12 '11 at 19:17









                                                                  UlfUlf

                                                                  91




                                                                  91























                                                                      0














                                                                      Assume we rsync Oracle DB backups to a tertiary disk manually. Then we want to delete old backups on that disk. So here is a small bash script:



                                                                      #!/bin/sh

                                                                      for backup_dir in {'/backup/cmsprd/local/backupset','/backup/cmsprd/local/autobackup','/backup/cfprd/backupset','/backup/cfprd/autobackup'}
                                                                      do

                                                                      for f in `find $backup_dir -type d -regex '.*_.*_.*' -printf "%fn"`
                                                                      do

                                                                      f2=`echo $f | sed -e 's/_//g'`
                                                                      days=$(((`date "+%s"` - `date -d "${f2}" "+%s"`)/86400))

                                                                      if [ $days -gt 30 ]; then
                                                                      rm -rf $backup_dir/$f
                                                                      fi

                                                                      done

                                                                      done


                                                                      Modify the dirs and retention period ("30 days") to suit your needs.






                                                                      share|improve this answer


























                                                                      • Oracle puts backup sets in Flash Recovery Area using format like 'YYYY_MM_DD' so we delete the underscores for passing it to 'date -d'

                                                                        – Alex Cherkas
                                                                        Feb 18 '13 at 8:52


















                                                                      0














                                                                      Assume we rsync Oracle DB backups to a tertiary disk manually. Then we want to delete old backups on that disk. So here is a small bash script:



                                                                      #!/bin/sh

                                                                      for backup_dir in {'/backup/cmsprd/local/backupset','/backup/cmsprd/local/autobackup','/backup/cfprd/backupset','/backup/cfprd/autobackup'}
                                                                      do

                                                                      for f in `find $backup_dir -type d -regex '.*_.*_.*' -printf "%fn"`
                                                                      do

                                                                      f2=`echo $f | sed -e 's/_//g'`
                                                                      days=$(((`date "+%s"` - `date -d "${f2}" "+%s"`)/86400))

                                                                      if [ $days -gt 30 ]; then
                                                                      rm -rf $backup_dir/$f
                                                                      fi

                                                                      done

                                                                      done


                                                                      Modify the dirs and retention period ("30 days") to suit your needs.






                                                                      share|improve this answer


























                                                                      • Oracle puts backup sets in Flash Recovery Area using format like 'YYYY_MM_DD' so we delete the underscores for passing it to 'date -d'

                                                                        – Alex Cherkas
                                                                        Feb 18 '13 at 8:52
















                                                                      0












                                                                      0








                                                                      0







                                                                      Assume we rsync Oracle DB backups to a tertiary disk manually. Then we want to delete old backups on that disk. So here is a small bash script:



                                                                      #!/bin/sh

                                                                      for backup_dir in {'/backup/cmsprd/local/backupset','/backup/cmsprd/local/autobackup','/backup/cfprd/backupset','/backup/cfprd/autobackup'}
                                                                      do

                                                                      for f in `find $backup_dir -type d -regex '.*_.*_.*' -printf "%fn"`
                                                                      do

                                                                      f2=`echo $f | sed -e 's/_//g'`
                                                                      days=$(((`date "+%s"` - `date -d "${f2}" "+%s"`)/86400))

                                                                      if [ $days -gt 30 ]; then
                                                                      rm -rf $backup_dir/$f
                                                                      fi

                                                                      done

                                                                      done


                                                                      Modify the dirs and retention period ("30 days") to suit your needs.






                                                                      share|improve this answer















                                                                      Assume we rsync Oracle DB backups to a tertiary disk manually. Then we want to delete old backups on that disk. So here is a small bash script:



                                                                      #!/bin/sh

                                                                      for backup_dir in {'/backup/cmsprd/local/backupset','/backup/cmsprd/local/autobackup','/backup/cfprd/backupset','/backup/cfprd/autobackup'}
                                                                      do

                                                                      for f in `find $backup_dir -type d -regex '.*_.*_.*' -printf "%fn"`
                                                                      do

                                                                      f2=`echo $f | sed -e 's/_//g'`
                                                                      days=$(((`date "+%s"` - `date -d "${f2}" "+%s"`)/86400))

                                                                      if [ $days -gt 30 ]; then
                                                                      rm -rf $backup_dir/$f
                                                                      fi

                                                                      done

                                                                      done


                                                                      Modify the dirs and retention period ("30 days") to suit your needs.







                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited Mar 19 '13 at 18:13









                                                                      Community

                                                                      11




                                                                      11










                                                                      answered Feb 18 '13 at 8:49









                                                                      Alex CherkasAlex Cherkas

                                                                      15113




                                                                      15113













                                                                      • Oracle puts backup sets in Flash Recovery Area using format like 'YYYY_MM_DD' so we delete the underscores for passing it to 'date -d'

                                                                        – Alex Cherkas
                                                                        Feb 18 '13 at 8:52





















                                                                      • Oracle puts backup sets in Flash Recovery Area using format like 'YYYY_MM_DD' so we delete the underscores for passing it to 'date -d'

                                                                        – Alex Cherkas
                                                                        Feb 18 '13 at 8:52



















                                                                      Oracle puts backup sets in Flash Recovery Area using format like 'YYYY_MM_DD' so we delete the underscores for passing it to 'date -d'

                                                                      – Alex Cherkas
                                                                      Feb 18 '13 at 8:52







                                                                      Oracle puts backup sets in Flash Recovery Area using format like 'YYYY_MM_DD' so we delete the underscores for passing it to 'date -d'

                                                                      – Alex Cherkas
                                                                      Feb 18 '13 at 8:52













                                                                      0














                                                                      Use the shell functions from http://cfajohnson.com/shell/ssr/ssr-scripts.tar.gz; they work in any standard Unix shell.



                                                                      date1=2012-09-22
                                                                      date2=2013-01-31
                                                                      . date-funcs-sh
                                                                      _date2julian "$date1"
                                                                      jd1=$_DATE2JULIAN
                                                                      _date2julian "$date2"
                                                                      echo $(( _DATE2JULIAN - jd1 ))


                                                                      See the documentation at http://cfajohnson.com/shell/ssr/08-The-Dating-Game.shtml






                                                                      share|improve this answer






























                                                                        0














                                                                        Use the shell functions from http://cfajohnson.com/shell/ssr/ssr-scripts.tar.gz; they work in any standard Unix shell.



                                                                        date1=2012-09-22
                                                                        date2=2013-01-31
                                                                        . date-funcs-sh
                                                                        _date2julian "$date1"
                                                                        jd1=$_DATE2JULIAN
                                                                        _date2julian "$date2"
                                                                        echo $(( _DATE2JULIAN - jd1 ))


                                                                        See the documentation at http://cfajohnson.com/shell/ssr/08-The-Dating-Game.shtml






                                                                        share|improve this answer




























                                                                          0












                                                                          0








                                                                          0







                                                                          Use the shell functions from http://cfajohnson.com/shell/ssr/ssr-scripts.tar.gz; they work in any standard Unix shell.



                                                                          date1=2012-09-22
                                                                          date2=2013-01-31
                                                                          . date-funcs-sh
                                                                          _date2julian "$date1"
                                                                          jd1=$_DATE2JULIAN
                                                                          _date2julian "$date2"
                                                                          echo $(( _DATE2JULIAN - jd1 ))


                                                                          See the documentation at http://cfajohnson.com/shell/ssr/08-The-Dating-Game.shtml






                                                                          share|improve this answer















                                                                          Use the shell functions from http://cfajohnson.com/shell/ssr/ssr-scripts.tar.gz; they work in any standard Unix shell.



                                                                          date1=2012-09-22
                                                                          date2=2013-01-31
                                                                          . date-funcs-sh
                                                                          _date2julian "$date1"
                                                                          jd1=$_DATE2JULIAN
                                                                          _date2julian "$date2"
                                                                          echo $(( _DATE2JULIAN - jd1 ))


                                                                          See the documentation at http://cfajohnson.com/shell/ssr/08-The-Dating-Game.shtml







                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Jun 18 '13 at 17:35









                                                                          jaypal singh

                                                                          57.7k1582121




                                                                          57.7k1582121










                                                                          answered Feb 2 '13 at 3:30









                                                                          Chris F.A. JohnsonChris F.A. Johnson

                                                                          1711




                                                                          1711























                                                                              0














                                                                              Using mysql command



                                                                              $ echo "select datediff('2013-06-20 18:12:54+08:00', '2013-05-30 18:12:54+08:00');"  | mysql -N


                                                                              Result: 21



                                                                              NOTE: Only the date parts of the values are used in the calculation



                                                                              Reference: http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_datediff






                                                                              share|improve this answer




























                                                                                0














                                                                                Using mysql command



                                                                                $ echo "select datediff('2013-06-20 18:12:54+08:00', '2013-05-30 18:12:54+08:00');"  | mysql -N


                                                                                Result: 21



                                                                                NOTE: Only the date parts of the values are used in the calculation



                                                                                Reference: http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_datediff






                                                                                share|improve this answer


























                                                                                  0












                                                                                  0








                                                                                  0







                                                                                  Using mysql command



                                                                                  $ echo "select datediff('2013-06-20 18:12:54+08:00', '2013-05-30 18:12:54+08:00');"  | mysql -N


                                                                                  Result: 21



                                                                                  NOTE: Only the date parts of the values are used in the calculation



                                                                                  Reference: http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_datediff






                                                                                  share|improve this answer













                                                                                  Using mysql command



                                                                                  $ echo "select datediff('2013-06-20 18:12:54+08:00', '2013-05-30 18:12:54+08:00');"  | mysql -N


                                                                                  Result: 21



                                                                                  NOTE: Only the date parts of the values are used in the calculation



                                                                                  Reference: http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_datediff







                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Jun 20 '13 at 10:25









                                                                                  brucebruce

                                                                                  29713




                                                                                  29713























                                                                                      0














                                                                                      This assumes that a month is 1/12 of a year:



                                                                                      #!/usr/bin/awk -f
                                                                                      function mktm(datespec) {
                                                                                      split(datespec, q, "-")
                                                                                      return q[1] * 365.25 + q[3] * 365.25 / 12 + q[2]
                                                                                      }
                                                                                      BEGIN {
                                                                                      printf "%dn", mktm(ARGV[2]) - mktm(ARGV[1])
                                                                                      }





                                                                                      share|improve this answer




























                                                                                        0














                                                                                        This assumes that a month is 1/12 of a year:



                                                                                        #!/usr/bin/awk -f
                                                                                        function mktm(datespec) {
                                                                                        split(datespec, q, "-")
                                                                                        return q[1] * 365.25 + q[3] * 365.25 / 12 + q[2]
                                                                                        }
                                                                                        BEGIN {
                                                                                        printf "%dn", mktm(ARGV[2]) - mktm(ARGV[1])
                                                                                        }





                                                                                        share|improve this answer


























                                                                                          0












                                                                                          0








                                                                                          0







                                                                                          This assumes that a month is 1/12 of a year:



                                                                                          #!/usr/bin/awk -f
                                                                                          function mktm(datespec) {
                                                                                          split(datespec, q, "-")
                                                                                          return q[1] * 365.25 + q[3] * 365.25 / 12 + q[2]
                                                                                          }
                                                                                          BEGIN {
                                                                                          printf "%dn", mktm(ARGV[2]) - mktm(ARGV[1])
                                                                                          }





                                                                                          share|improve this answer













                                                                                          This assumes that a month is 1/12 of a year:



                                                                                          #!/usr/bin/awk -f
                                                                                          function mktm(datespec) {
                                                                                          split(datespec, q, "-")
                                                                                          return q[1] * 365.25 + q[3] * 365.25 / 12 + q[2]
                                                                                          }
                                                                                          BEGIN {
                                                                                          printf "%dn", mktm(ARGV[2]) - mktm(ARGV[1])
                                                                                          }






                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Dec 29 '16 at 3:35









                                                                                          Steven PennySteven Penny

                                                                                          1




                                                                                          1























                                                                                              0














                                                                                              For MacOS sierra (maybe from Mac OS X yosemate),



                                                                                              To get epoch time(Seconds from 1970) from a file, and save it to a var:

                                                                                              old_dt=`date -j -r YOUR_FILE "+%s"`



                                                                                              To get epoch time of current time

                                                                                              new_dt=`date -j "+%s"`



                                                                                              To calculate difference of above two epoch time

                                                                                              (( diff = new_dt - old_dt ))



                                                                                              To check if diff is more than 23 days

                                                                                              (( new_dt - old_dt > (23*86400) )) && echo Is more than 23 days






                                                                                              share|improve this answer




























                                                                                                0














                                                                                                For MacOS sierra (maybe from Mac OS X yosemate),



                                                                                                To get epoch time(Seconds from 1970) from a file, and save it to a var:

                                                                                                old_dt=`date -j -r YOUR_FILE "+%s"`



                                                                                                To get epoch time of current time

                                                                                                new_dt=`date -j "+%s"`



                                                                                                To calculate difference of above two epoch time

                                                                                                (( diff = new_dt - old_dt ))



                                                                                                To check if diff is more than 23 days

                                                                                                (( new_dt - old_dt > (23*86400) )) && echo Is more than 23 days






                                                                                                share|improve this answer


























                                                                                                  0












                                                                                                  0








                                                                                                  0







                                                                                                  For MacOS sierra (maybe from Mac OS X yosemate),



                                                                                                  To get epoch time(Seconds from 1970) from a file, and save it to a var:

                                                                                                  old_dt=`date -j -r YOUR_FILE "+%s"`



                                                                                                  To get epoch time of current time

                                                                                                  new_dt=`date -j "+%s"`



                                                                                                  To calculate difference of above two epoch time

                                                                                                  (( diff = new_dt - old_dt ))



                                                                                                  To check if diff is more than 23 days

                                                                                                  (( new_dt - old_dt > (23*86400) )) && echo Is more than 23 days






                                                                                                  share|improve this answer













                                                                                                  For MacOS sierra (maybe from Mac OS X yosemate),



                                                                                                  To get epoch time(Seconds from 1970) from a file, and save it to a var:

                                                                                                  old_dt=`date -j -r YOUR_FILE "+%s"`



                                                                                                  To get epoch time of current time

                                                                                                  new_dt=`date -j "+%s"`



                                                                                                  To calculate difference of above two epoch time

                                                                                                  (( diff = new_dt - old_dt ))



                                                                                                  To check if diff is more than 23 days

                                                                                                  (( new_dt - old_dt > (23*86400) )) && echo Is more than 23 days







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Jun 11 '17 at 13:05









                                                                                                  osexp2003osexp2003

                                                                                                  1,3901215




                                                                                                  1,3901215






























                                                                                                      draft saved

                                                                                                      draft discarded




















































                                                                                                      Thanks for contributing an answer to Stack Overflow!


                                                                                                      • Please be sure to answer the question. Provide details and share your research!

                                                                                                      But avoid



                                                                                                      • Asking for help, clarification, or responding to other answers.

                                                                                                      • Making statements based on opinion; back them up with references or personal experience.


                                                                                                      To learn more, see our tips on writing great answers.




                                                                                                      draft saved


                                                                                                      draft discarded














                                                                                                      StackExchange.ready(
                                                                                                      function () {
                                                                                                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4946785%2fhow-to-find-the-difference-in-days-between-two-dates%23new-answer', 'question_page');
                                                                                                      }
                                                                                                      );

                                                                                                      Post as a guest















                                                                                                      Required, but never shown





















































                                                                                                      Required, but never shown














                                                                                                      Required, but never shown












                                                                                                      Required, but never shown







                                                                                                      Required, but never shown

































                                                                                                      Required, but never shown














                                                                                                      Required, but never shown












                                                                                                      Required, but never shown







                                                                                                      Required, but never shown







                                                                                                      Popular posts from this blog

                                                                                                      Callistus III

                                                                                                      Ostreoida

                                                                                                      Index Sanctorum