applescript - 将 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;
额外的问题......我们所处时代的整数值是多少?
解决方案
尽管 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。
推荐阅读
- java - listFiles 的方法引用
- json - 在 Spark Scala 中使用 blob 元素编写 JSON 字符串数组
- bash - 在 PostgreSQL 12 上使用单个 CLI 命令终止所有打开的连接
- go - Go中File和Writer之间的关系是什么?
- android-studio - 如何使用 Firebase Android Studio 向个人电子邮件发送电子邮件验证
- python - PYTHON:如何让 seaborn 属性重置为默认值?
- matlab - 图论 Matlab BFS 算法
- typescript - Typescript Postmessage 失败,有一个参数,两个
- java - 他们是否在 makefile 文档中指定了两次编译?
- java - 从 K8S ConfigMap 文件中将嵌套的 JSON 读入 Spring 配置 bean