Search code examples
applescriptapplescript-objc

Converting AppleScript Date into an NSdate object in ASOBJC?


So I have some AppleScriptObjC code that does some things with dates. One of the first things it does is convert todays date into an NSDate object.

set nowDate to current application's NSDate's |date|()

I'd like to be able to set nowDate to any date I choose. From everything I have read, up until 10.11 this was a very complex process. But in 10.11 it supposedly got easier. I couldn't actually find any examples on how it was easier.

What I'd really like is to be able to say

    set aDate to current date
    set day of aDate to "15"
    set month of aDate to "5"
    set year of aDate to "2020"
    set hours of aDate to "13"
    set minutes of aDate to "00"
    set seconds of aDate to "00"

    set nowDate to NSDate's aDate --or something simple like that

I also found this function that looks to be able to set a date to any date you would like, but I have not idea how to convert this into useful ASOBJC code (I fumbled around a bit with it, but got nowhere):

- (NSDate *)dateWithEra:(NSInteger)eraValue 
                   year:(NSInteger)yearValue 
                  month:(NSInteger)monthValue 
                    day:(NSInteger)dayValue 
                   hour:(NSInteger)hourValue 
                 minute:(NSInteger)minuteValue 
                 second:(NSInteger)secondValue 
             nanosecond:(NSInteger)nanosecondValue;

Bonus question... what is the integer value for the era we are in?


Solution

  • Although AppleScriptObjC will easily convert an NSDate to an AppleScript date, there isn't anything quite that simple for going the other way.

    There is something quite simple: AppleScript date is implicitly bridged to NSDate when being used as a parameter so you can convert it easily with

    use AppleScript version "2.5"
    use framework "Foundation"
    use scripting additions
    
    set currentDate to current date
    set cocoaDate to current application's NSDate's dateWithTimeInterval:0 sinceDate:currentDate
    log cocoaDate