LoginSignup
3
3

More than 5 years have passed since last update.

Cocoaの機能を使って日付と文字列を変換するAppleScriptハンドラ

Last updated at Posted at 2016-01-06
  • dateFromStringUsingFormat: dateFormatをフォーマットとしてdateStringを日付に変換
  • formatDate: dateFormatをフォーマットとしてaDateを文字列に変換
  • convertDateExpression: inputDateStringの日付表記をinputDateFormatからoutputDateFormatに変換
use scripting additions
use framework "Foundation"
property dateFormatter : missing value

log dateFromStringUsingFormat("2013/11/02 13:04:55", "yyyy/MM/dd HH:mm:ss") as date
--> date "2013年11月2日土曜日 13:04:55"

log formatDate(current date, "yyyy-MM-dd HH:mm:ss") as text
--> "2016-01-06 17:09:49"

log convertDateExpression("2013/11/02 13:04:55", "yyyy/MM/dd HH:mm:ss", "M'月'd'日' ah'時'm'分'") as text
--> "11月2日 午後1時4分"

on dateFromStringUsingFormat(dateString, dateFormat)
    return dateFormatterWithFormat(dateFormat)'s dateFromString:dateString
end dateFromStringUsingFormat

on formatDate(aDate, dateFormat)
    return dateFormatterWithFormat(dateFormat)'s stringFromDate:aDate
end formatDate

on convertDateExpression(inputDateString, inputDateFormat, outputDateFormat)
    set aDate to dateFormatterWithFormat(inputDateFormat)'s dateFromString:inputDateString
    return dateFormatterWithFormat(outputDateFormat)'s stringFromDate:aDate
end convertDateExpression

on dateFormatterWithFormat(format)
    --require framework: Foundation
    try
        if dateFormatter = missing value then
            error number -2753
        end if
    on error number -2753
        set dateFormatter to current application's NSDateFormatter's alloc()'s init()
        set dateFormatter's locale to current application's NSLocale's localeWithLocaleIdentifier:"en_US_POSIX"
        set dateFormatter's timeZone to current application's NSTimeZone's defaultTimeZone
    end try
    set dateFormatter's dateFormat to format
    return dateFormatter
end dateFormatterWithFormat

更新履歴

  • 2016-01-06: Cocoaの機能を使って作成
  • 2016-01-07: use文を冒頭に記述
  • 2016-01-17: setTimeZonetime to GMTを追加して、タイムゾーンによる時刻のズレを修正
  • 2016-01-20: localeとtimeZoneを設定
  • 2016-01-22: dateFormatterの初期宣言部分をdateFormatterWithFormatハンドラにまとめ
  • 2018-09-14: dateFormatterをキャッシュするように変更
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3