首页 > 解决方案 > 将 AppleScript 日期转换为 ASOBJC 中的 NSdate 对象?

问题描述

所以我有一些 AppleScriptObjC 代码可以处理日期。它所做的第一件事就是将今天的日期转换为 NSDate 对象。

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

我希望能够设置nowDate为我选择的任何日期。从我读过的所有内容来看,直到 10.11,这是一个非常复杂的过程。但在 10.11 中,它应该变得更容易了。我实际上找不到任何关于它如何更容易的例子。

我真正想要的是能够说

    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

我还发现这个函数看起来可以将日期设置为您想要的任何日期,但我不知道如何将其转换为有用的 ASOBJC 代码(我摸索了一下,但一无所获):

- (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;

额外的问题......我们所处时代的整数值是多少?

标签: applescriptapplescript-objc

解决方案


尽管 AppleScriptObjC 可以轻松地将 NSDate 强制转换为 AppleScript 日期,但要采用另一种方式并没有那么简单。Cocoa 有很多日期选项,因此您需要使用一些语句来定义您想要的内容。

您的 Objective-C 方法的转换类似于(不要忘记 AppleScript 术语周围的管道):

use framework "Foundation"
use scripting additions

tell (current date) to set {theDay, theMonth, theYear, theHours, theMinutes, theSeconds} to {its day, its month as integer, its year, its hours, its minutes, its seconds}

set theCalendar to current application's NSCalendar's currentCalendar
theCalendar's dateWithEra:1 |year|:theYear |month|:theMonth |day|:theDay hour:theHours minute:theMinutes |second|:theSeconds nanosecond:0

您还可以使用NSDateFormatter从 ISO 日期字符串进行转换:

tell ((current date) as «class isot» as string) to set dateString to it

set formatter to current application's NSDateFormatter's alloc's init
formatter's setDateFormat:"yyyy-MM-dd'T'HH:mm:ss"
# formatter's setLocale:(current application's NSLocale's alloc's initWithLocaleIdentifier:"en_US_POSIX")
formatter's dateFromString:dateString

对于您的额外问题,这取决于使用的日历,但对于公历有两个时代,BCE/BC 和 CE/AD。从 Apple's Date and Time Guide中,如果您对 BCE 使用负年份,则时代将为 0,否则将为 1。


推荐阅读