Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.
  • 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をキャッシュするように変更
szk-3
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away