Applescript “无法将”2023 年 4 月 1 日星期六 16:05:41“设置为键入日期。

Applescript "Can’t make "Saturday, April 1, 2023 at 16:05:41" into type date."

提问人:Rich 提问时间:4/1/2023 最后编辑:Rich 更新时间:4/2/2023 访问量:175

问:

信不信由你,我已经在谷歌上搜索了这个简单的东西,但在任何地方都找不到它。我有一个字符串,其日期为“YYYY-MM-DD”,但我是从 shell 脚本生成的,所以它可以是任何东西。 然而,Applescript 似乎只接受一种非常特定的字符串格式,我无法猜测,也找不到文档。我尝试了我能想到的所有格式。令人震惊的是,我什至无法让这段代码工作,它采用Applescript自己的格式并反馈它:

set theDate to (current date) as string
set tDate to theDate as date

因此,applescript 发出错误“无法将”2023 年 4 月 1 日星期六 14:49:59“转换为键入日期。 这怎么可能?谁能告诉我神奇的格式? 我知道这可能取决于我的系统设置,但是我如何找到我现在的设置并为脚本提供正确的字符串?
谢谢!

如果我查看Applescript词典,它提供了一个非描述性的答案。只是说“在构造日期时,您可以使用任何可以解释为日期、时间或日期时间的字符串值。请举例说明?

enter image description here enter image description here

字符串 datetime applescript

评论

0赞 Mockman 4/1/2023
简单的搜索将生成几个结果,这些结果具有此问题的解决方案。我认为这个问题应该作为重复的问题关闭,但至少它应该显示一些研究,而不是看字典,顺便说一句,字典确实提供了解决方案,尽管很简洁:——你不是在强迫(因为你已经强迫日期到文本,如字典中所述)。[applescript] datedate theDate
1赞 Mockman 4/1/2023
选择。。。 (或系统偏好设置中的任何日期格式)或甚至(在强制下),.date "2022-1-31"date "march 31, 2022"set xy to {y:2021, m:11, d:25}date "8:30" of date ((y of xy & "-" & m of xy & "-" & d of xy) as text)

答:

1赞 vadian 4/1/2023 #1

您不能将字符串强制为 ,但可以通过这种方式从字符串创建日期date

set theDate to (current date) as string
set tDate to date theDate
2赞 Robert Kniazidis 4/2/2023 #2

相关话题已经被咀嚼过很多次了。我只重复一下应该专门适用于“YYYY-MM-DD”的情况。

你在这里有错误的问题。关键是您需要根据您所在区域设置中的顺序放置“YYYY-MM-DD”的顺序。在不同的区域设置中,“年”、“月”、“日”的顺序是不同的,并且通常不是“YYYY-MM-DD”。

AppleScript 无法仅通过强制自动猜测正确的顺序。这是行不通的。而且,这是意料之外的。例如,AppleScript 如何辨别成对的一天和月(“11”、“05”)?不可能。

因此,您必须通过编写正确的转换(最好作为处理程序)来显式指定顺序

myShellStringDateToAppleScriptDate("2024-11-05") -- string's order is not localized: YYYY-MM-DD

on myShellStringDateToAppleScriptDate(shellDate)
    set AppleScriptDate to (current date) -- creates new date object with localized order
    tell AppleScriptDate -- put the order of "YYYY-MM-DD" in accordance with the order in your locale
        set year to text 1 thru 4 of shellDate
        set its month to text 6 thru 7 of shellDate
        set day to text 9 thru 10 of shellDate
    end tell
    return AppleScriptDate
end myShellStringDateToAppleScriptDate

注意

Shell 提供了一种传递日期的方法,并指示本地化顺序。有一个所谓的 ISOT 字符串。通过 shell 在远程用户之间正确传输日期需要 ISOT 格式。给定一个 ISOT 字符串,您可以使用 AsObjC 代码将其转换为 AppleScript 日期:

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

set isotDate to "2020-05-07T06:05:34Z" -- ISOT string returned from shell
set formatter to current application's NSISO8601DateFormatter's new()
set theAppleScriptDate to (formatter's dateFromString:isotDate) as date
set theAppleScriptDate to theAppleScriptDate - (time to GMT)

最后,AsObjC 也可以通过显式指定 shell 字符串格式来使用:

use framework "Foundation"
use scripting additions

set todaysDate to do shell script "date '+%Y-%m-%d'" --> "2023-04-02"

set df to current application's NSDateFormatter's new()
df's setDateFormat:"y-M-d" -- related "YYYY-MM-DD" format
set theDate to (df's dateFromString:todaysDate) as date