Displaying Durations For Long Running Scripts

A handy tip, especially when developing a long-running script, is to display how long it took upon completion. This can help give you a feel for whether changes have had an effect on performance. But displaying values in raw seconds can look a bit, well, unprofessional, and doing the divisions to make minutes and seconds (and in some cases hours) is tedious. NSDateComponentsFormatter can help.

Let’s say your timer has produce the result timeTaken of 856 seconds. Here’s some simple code:

use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

set timeTaken to 856 -- for testing

set dcFormatter to current application's NSDateComponentsFormatter's new()
set timeString to (dcFormatter's stringFromTimeInterval:timeTaken) as text
--> "14:16"

You can control how compact the format is. For example:

set timeTaken to 856 -- for testing
set dcFormatter to current application's NSDateComponentsFormatter's new()
dcFormatter's setUnitsStyle:(current application's NSDateComponentsFormatterUnitsStyleFull)
set timeString to (dcFormatter's stringFromTimeInterval:timeTaken) as text
--> "14 minutes, 16 seconds"

You can also add things like a localized approximation phrase, let the formatter deal directly with two dates (but they must be NSDates before macOS 10.11):

set startDate to current application's NSDate's |date|()
set endDate to startDate's dateByAddingTimeInterval:6789
set dcFormatter to current application's NSDateComponentsFormatter's new()
dcFormatter's setUnitsStyle:(current application's NSDateComponentsFormatterUnitsStyleShort)
dcFormatter's setIncludesApproximationPhrase:true
set timeString to (dcFormatter's stringFromDate:startDate toDate:endDate) as text
--> "About 1 hr, 53 min., 9 sec."
5 Likes