Date-/Time-Calculations using AppleScript

This short how-to explains how you calculate with time- and date-values in AppleScript. Quite a few people told me, that they are using the do shell script-handler presented in the post How to convert an “epoch”-time to a meaningful date and time. Nothing wrong with that, but if you just want to perform time-calculations inside an AppleScript, then there is an easier way.

If you assign the current time to a variable as in set myDate to current date and you just want to calculate the current date plus 2 days, then there is no need to use epoch-seconds.

  1. set myNewDate to myDate + (2 * days), adds 2 days to the date and time stored in myDate.
  2. set myNewDate to myDate + (4 * hours), adds 4 hours to the current time and date.
  3. set myNewDate to myDate + (30 * minutes), adds 30 minutes to the current time and date.

It is really that simple, AppleScript uses epoch-seconds to perform these calculations, so you don’t have to. ;)

If you need to set the date and time to the beginning of the current day, then use

set myTime to time of myDate

set myNewDate to myDate - myTime

The variable myNewDate now contains the current date and 00:00:00 as time.

Epoch-seconds are great if you want to store a date-value and read it back in later, but as long as you stay inside an AppleScript, there is no need to resort to epoch-values.

4 Comments

  1. Grover
    Posted September 28, 2008 at 5:43 pm | Permalink

    Bless you kind sir. I just spent hours looking for this information.

  2. Posted September 29, 2008 at 7:50 am | Permalink

    Glad to hear that. Apple has a tendency to “hide” crucial information, took a while to figure this out. :)

  3. Posted October 12, 2008 at 9:41 pm | Permalink

    Maybe you know how to get month as integer without the “if myMonth is january then set myM to 01″?

  4. Posted October 13, 2008 at 6:35 am | Permalink

    Per, the fastest way I’m aware of is:

    set theDate to current date
    copy theDate to b
    set the month of b to January
    set monthNum to (1 + (theDate - b + 1314864) div 2629728)

    “monthNum” should now contain the month as int.

    Hope this helps.

Post a Comment

Your email is never published nor shared. Required fields are marked *, comments are moderated.

*
*