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.
set myNewDate to myDate + (2 * days), adds 2 days to the date and time stored inmyDate.set myNewDate to myDate + (4 * hours), adds 4 hours to the current time and date.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
Bless you kind sir. I just spent hours looking for this information.
Glad to hear that. Apple has a tendency to “hide” crucial information, took a while to figure this out.
Maybe you know how to get month as integer without the “if myMonth is january then set myM to 01″?
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.