2008-12-05 08:58:09 daysSince
A tiny script I needed a few times to quickly tell me how many days it's been since a given date at the command line. I wrote it in f-script (i.e., this is Mac-specific). I could have compressed the code in the middle, but I wanted to keep it ultra-understandable. (As as side-note, "NSDate date" means today's date.)

Post other versions in other languages if you feel so inclined.

( fscript )
  1  #!/usr/bin/fscript
2 (sys args count > 0) ifTrue:[
3
4 then := NSDate dateWithNaturalLanguageString:(sys args at:0).
5 seconds := NSDate date timeIntervalSinceDate:then.
6 secsPerDay := 60 * 60 * 24.
7 days := seconds / secsPerDay.
8 sys out println:(days stringValue) ++ ' days ago'.
9
10 ] ifFalse:[ sys out println:'usage: daysSince (date)' ].
  • Jeff (Mon, December 15th, 2008, 6:04pm UTC)
    I'll add a Python version here. I thought Python might have a more elegant way to handle this, and perhaps someone knows how to make this more natural.

    ( python )
      1  #!/usr/bin/python
    2 import datetime, sys
    3
    4 if len( sys.argv )!=2:
    5 print "Usage: daysSince (date)"
    6 else:
    7 today = datetime.date.today()
    8 year, month, day = [ int(i) for i in sys.argv[1].split( '-' ) ]
    9 then = datetime.date( year, month, day )
    10 print str( (today-then).days ) + " days ago"

  • Philippe Mougin (Mon, January 12th, 2009, 2:30pm UTC)
    Hi Jeff,

    I see a couple of potentially interesting simplifications in the F-Script code :

    NSDate dateWithNaturalLanguageString:(sys args at:0)

    can be repalced by:

    (sys args at:0) asDate

    -------

    NSDate date timeIntervalSinceDate:then

    can be replaced by

    NSDate date — then

    In addition, you don't need to surround "sys args count > 0" and "days stringValue" with parentheses.


  • Jeff (Mon, January 12th, 2009, 3:09pm UTC)
    Thanks for the info, Philippe. I think I'll still keep the parentheses for clarity, but I'm really happy to learn about the NSDate algebra and the asDate method. I also then added a check on the then date, which I should have had in there to begin with.

    So here's the updated script here:
    ( fscript )
      1  #!/usr/bin/fscript
    2 (sys args count > 0) ifTrue:[
    3
    4 then := (sys args at:0) asDate.
    5 (then==nil) ifFalse:[
    6
    7 seconds := NSDate date — then.
    8 daysPerSec := 60 * 60 * 24.
    9 days := seconds / daysPerSec.
    10 sys out println:(days stringValue) ++ ' days ago'.
    11
    12 ] ifTrue:[ sys out println:'invalid date string' ]
    13
    14 ] ifFalse:[ sys out println:'usage: daysSince (date)' ].

Leave a comment