Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: Calendar

指定Localeおよび現在のユーザー環境のLocaleから短縮曜日名を取得

Posted on 2月 16, 2019 by Takaaki Naganoya

指定の任意のLocaleもしくはScript実行中のユーザー環境のLocaleを取得して、曜日の短縮名称を取得するAppleScriptです。

AppleScript名:指定Localeおよび現在のユーザー環境のLocaleから短縮曜日名を取得
— Created 2019-02-14 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aList to getLocalizedShortDaynames("en_US")
–>  {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
set aList to getLocalizedShortDaynames("fr_FR")
–>  {"dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."}
set aList to getLocalizedShortDaynames("ja_JP")
–>  {"日", "月", "火", "水", "木", "金", "土"}
set aList to getLocalizedShortDaynames("zh-Hans")
–>  {"周日", "周一", "周二", "周三", "周四", "周五", "周六"}

–現在のユーザーのLocale情報を取得して短縮曜日名を取得
set curLoc to (current application’s NSLocale’s currentLocale’s objectForKey:(current application’s NSLocaleIdentifier)) as string
–> "ja_JP"
set bList to getLocalizedShortDaynames(curLoc) of me
–> {"日", "月", "火", "水", "木", "金", "土"}

–ローカライズされた曜日名称を返す(短縮名称)
on getLocalizedShortDaynames(aLoc)
  set df to current application’s NSDateFormatter’s alloc()’s init()
  
df’s setLocale:(current application’s NSLocale’s localeWithLocaleIdentifier:aLoc)
  
set dayNames to df’s shortStandaloneWeekdaySymbols() as list
  
return dayNames
end getLocalizedShortDaynames

★Click Here to Open This Script 

Posted in Calendar Locale System | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy | Leave a comment

Keynoteの最前面のドキュメントの現在のスライドに指定月の日曜日はじまりカレンダーを表で作成

Posted on 2月 14, 2019 by Takaaki Naganoya

Keynoteの最前面の書類の現在選択中のスライド(ページ)に、指定月の日曜日はじまりカレンダーを、表オブジェクトで作成するAppleScriptです。

Keynoteで資料を作成していると、資料にカレンダーを入れたいケースが多々あります。Terminal.appを起動してcalコマンドでカレンダーを作ってみたり、Dashboardのカレンダーをコピーして入れることも多いですが、Dashboardはもうあるんだかないんだ分からない状態。かわりのものを用意してみました。

あとは、サイズやスタイル、土日のデータを削除するなど用途に応じて編集して表カレンダーを利用するとよいでしょう。

macOS標準装備のスクリプトメニューに入れて呼び出す場合には、アプリケーション形式で書き出したものを使う必要があります。

世の中のカレンダーは日曜日はじまりだけではないので、月曜日はじまりなど、その国、その現場ごとのルールに合わせて変更することが重要です。曜日名についても、実行中のユーザーの言語環境から取得して入れることも可能なので、そのようにしてもよいでしょう。

同じぐらいのスペックのマシンで本Scriptを動かすと、macOS 10.14, Mojave上では10.12.6上の(Keynote v8.1の)倍ぐらい速くて驚かされます。10.13.6上でも同様なのでOS側の対応というよりは、Keynote側のバージョンアップ(v8.1 –> v8.3)によるものかもしれません。

AppleScript名:指定月の日曜日はじまりカレンダーを表で作成 v2.scptd
— Created 2019-02-14 by Takaaki Naganoya
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property theDate : missing value

property daysList : {"日", "月", "火", "水", "木", "金", "土"} –Japanese
–property daysList : {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}–English

set paramObj to {myMessage:"月選択", mySubMessage:"作成対象の月を選択してください。日付はどれでもけっこうです。"}
set {targYear, targMonth} to chooseMonth(paramObj) of me

–指定月のカレンダーを1D List(7 days x 6 weeks) で作成
set aCalList to retListCalendar(targYear, targMonth) of me

set fullCalList to daysList & aCalList

set aTitle to (targYear as string) & (targMonth as string)
set dCount to 1

tell application "Keynote"
  tell front document
    tell current slide
      set aTable to make new table with properties {header column count:0, header row count:1, row count:7, column count:7, name:aTitle}
      
tell aTable
        repeat with i from 1 to 49
          tell cell i
            ignoring application responses
              set value to contents of item dCount of fullCalList
            end ignoring
          end tell
          
set dCount to dCount + 1
        end repeat
      end tell
    end tell
  end tell
end tell

–カレンダー作成対象の年、月を選択(ただし、日付をクリックして選択しないと値を取得できないので注意)
on chooseMonth(paramObj)
  my performSelectorOnMainThread:"chooseDate:" withObject:(paramObj) waitUntilDone:true
  
set aYear to year of theDate
  
set aMonth to month of theDate as number
  
return {aYear, aMonth}
end chooseMonth

on chooseDate:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
  
— create a view
  
set theView to current application’s NSView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 100, 200))
  
set datePicker to current application’s NSDatePicker’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 100, 100))
  
datePicker’s setDatePickerStyle:(current application’s NSClockAndCalendarDatePickerStyle)
  
datePicker’s setDatePickerElements:((current application’s NSYearMonthDayDatePickerElementFlag) + (current application’s NSHourMinuteSecondDatePickerElementFlag as integer))
  
  
datePicker’s setDateValue:(current application’s NSDate’s |date|())
  
  
set theSize to datePicker’s fittingSize()
  
  
theView’s setFrameSize:theSize
  
datePicker’s setFrameSize:theSize
  
  
theView’s setSubviews:{datePicker}
  
  
set theAlert to current application’s NSAlert’s alloc()’s init()
  
  
— set up alert
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
its addButtonWithTitle:"Cancel"
    
its setAccessoryView:theView
  end tell
  
  
— show alert in modal loop
  
set returnCode to theAlert’s runModal()
  
if returnCode = (current application’s NSAlertSecondButtonReturn) then error number -128
  
  
— retrieve date
  
set (my theDate) to (datePicker’s dateValue()) as date
  
end chooseDate:

–指定月のカレンダーを1D List(7 days x 6 weeks) で返す
on retListCalendar(tYear, tMonth)
  set mLen to getMlen(tYear, tMonth) of me
  
set aList to {}
  
  
set fDat to getDateInternational(tYear, tMonth, 1) of me
  
tell current application
    set aOffset to (weekday of fDat) as number
  end tell
  
  
–header gap
  
repeat (aOffset – 1) times
    set the end of aList to ""
  end repeat
  
  
–calendar body
  
repeat with i from 1 to mLen
    set the end of aList to (i as string)
  end repeat
  
  
–footer gap
  
repeat (42 – aOffset – mLen + 1) times
    set the end of aList to ""
  end repeat
  
  
return aList
end retListCalendar

–現在のカレンダーで指定年月の日数を返す(国際化対応版)
on getMlen(aYear as integer, aMonth as integer)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:1 hour:0 minute:0 |second|:0 nanosecond:0
  
set theResult to theNSCalendar’s rangeOfUnit:(current application’s NSDayCalendarUnit) inUnit:(current application’s NSMonthCalendarUnit) forDate:theDate
  
return |length| of theResult
end getMlen

–現在のカレンダーで指定年月のdate objectを返す
on getDateInternational(aYear, aMonth, aDay)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:0 minute:0 |second|:0 nanosecond:0
  
return theDate as date
end getDateInternational

★Click Here to Open This Script 

Posted in Calendar GUI list | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Keynote NSAlert NSAlertSecondButtonReturn NSCalendar NSClockAndCalendarDatePickerStyle NSDate NSDatePicker NSDayCalendarUnit NSHourMinuteSecondDatePickerElementFlag NSMonthCalendarUnit NSView NSYearMonthDayDatePickerElementFlag | Leave a comment

MacJournalで選択中のエントリの文中からdata detectorで日付を取得して作成日付に反映

Posted on 1月 8, 2019 by Takaaki Naganoya

MacJournalで選択中のjournal entryの文中(plain text content)からData Detector(NSDataDetector)で日付を取得し、初出の日付をjournal entryの作成日付に設定するAppleScriptです。

macOSの不具合情報をMacJournalにスクラップして整理していたところ、記事作成日をjournal entryの作成日付に反映させたいと考え、以前に作ってあったScriptを修正し、Data Detectorで日付情報を抽出するようにしてみました。

なお、複数のjournal entryを選択した状態で実行すると、ループですべての選択中のjournal entryを処理します。

macOS標準搭載のScript Menuに入れて使用しています。

AppleScript名:MacJournalで選択中のエントリの文中からdata detectorで日付を取得して作成日付に反映
— Created 2019-01-08 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSString : a reference to current application’s NSString
property NSDataDetector : a reference to current application’s NSDataDetector

tell application "MacJournal"
  set aSel to selected entries
  
  
repeat with i in aSel
    set j to contents of i
    
set aName to name of j
    
set aDate to date of j
    
set aStr to plain text content of j
    
set aDateList to getDatesIn(aStr) of me
    
    
if aStr is not equal to "" and aDateList is not equal to {} then
      set targDate to contents of (first item of aDateList)
      
try
        set date of j to targDate
      end try
    end if
  end repeat
end tell

on getDatesIn(aString)
  set anNSString to NSString’s stringWithString:aString
  
set {theDetector, theError} to NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeDate) |error|:(reference)
  
set theMatches to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
set theResults to theMatches’s valueForKey:"date"
  
return theResults as list
end getDatesIn

★Click Here to Open This Script 

Posted in Calendar Text | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy MacJournal NSDataDetector NSString | Leave a comment

ファイル作成日、修正日を変更する

Posted on 10月 29, 2018 by Takaaki Naganoya

指定ファイルの作成日、修正日を変更するAppleScriptです。

以前はsetFileコマンド(Xcodeのcommand lineユーティリティーをインストールすると入る)で行うパターンを掲載していたのですが、NSFileManagerの方が楽にできるのと、どの実行環境でも(開発ツールが入っていなくても)実行できていいと思います。

AppleScript名:ファイル作成日、修正日を変更する
— Created 2018-05-30 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aFile to POSIX path of (choose file)
set targDate to current date
changeFileCreationDate(targDate, aFile) of me
changeFileModDate(targDate, aFile) of me

–指定パスのファイルの作成日時を変更する
on changeFileCreationDate(aDate, aFile)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithObject:aDate forKey:(current application’s NSFileCreationDate)
  
set aFM to current application’s NSFileManager’s defaultManager()’s setAttributes:aDic ofItemAtPath:(POSIX path of aFile) |error|:(missing value)
end changeFileCreationDate

–指定パスのファイルの修正日時を変更する
on changeFileModDate(aDate, aFile)
  set aDic to current application’s NSMutableDictionary’s dictionaryWithObject:aDate forKey:(current application’s NSFileModificationDate)
  
set aFM to current application’s NSFileManager’s defaultManager()’s setAttributes:aDic ofItemAtPath:(POSIX path of aFile) |error|:(missing value)
end changeFileModDate

★Click Here to Open This Script 

Posted in Calendar file File path | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSFileManager NSMutableDictionary | 1 Comment

スリープ復帰日時を設定する v2

Posted on 10月 29, 2018 by Takaaki Naganoya

指定の日時(年月日時分秒)にスリープ復帰日時を設定するAppleScriptです。

過去に掲載した記事の再掲載分ですが、以前に掲載したリストにバグが見つかったので修正しておきました。サブルーチン内でパラメータの変数と同じ名前の変数に代入してしまい、計算結果がおかしくなるという超恥ずかしいバグでした。

AppleScript名:スリープ復帰日時を設定する v2
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aYear to 2018 –年
set aMonth to 10 –月
set aDate to 30 –日

set aHour to 7 –時
set aMinute to 1 –分
set aSecond to 2 –秒

set myAccount to do shell script "whoami" –他に管理者アカウントを指定することも可。その場合にはmyPasswordには管理者のパスワードを指定
set myPassword to "" –パスワード(カラのままでOK。必要に応じてAS側からダイアログ入力を求める)

set pRes to setAwakeDate(aYear, aMonth, aDate, aHour, aMinute, aSecond, myAccount, myPassword) of me

–スリープからの復帰日時を設定する
on setAwakeDate(aYear, aMonth, aDate, aHour, aMinute, aSecond, myAccount, myPassword)
  if myPassword = "" then
    set myPassword to text returned of (display dialog "パスワードを入力してください" default answer "" with hidden answer)
  end if
  
  
–現在のユーザーに管理権限がない場合にはリターン
  
if getUsersPrivileges(myAccount) of me = false then return false
  
  
–過去の日時を指定していたら設定しない(過去掲載時にここが間違っていたので修正)
  
set tmpDate to getDateInternational(aYear, aMonth, aDate, aHour, aMinute, aSecond, "JST")
  
if ((current date) > tmpDate) then return false
  
  
–数値の整形(日付)
  
set tYear to retZeroPaddingText(aYear, 2) of me
  
set tMonth to retZeroPaddingText(aMonth, 2) of me
  
set tDate to retZeroPaddingText(aDate, 2) of me
  
  
–数値の整形(時刻)
  
set tHour to retZeroPaddingText(aHour, 2) of me
  
set tMinute to retZeroPaddingText(aMinute, 2) of me
  
set tSecond to retZeroPaddingText(aSecond, 2) of me
  
  
set tDateStr to (ASCII character 34) & tMonth & "/" & tDate & "/" & tYear & " " & tHour & ":" & tMinute & ":" & tSecond & (ASCII character 34)
  
  
try
    set sRes to (do shell script "/usr/bin/pmset schedule wake " & tDateStr user name myAccount password myPassword with administrator privileges)
  on error erMes
    return erMes –時間を過去に設定したか、あるいは数値の範囲指定エラー。パスワードの指定ミスの可能性もあり得る
  end try
  
  
return true
  
end setAwakeDate

–指定ユーザーの権限を得る(管理者か、それ以外か) 10.4および10.5以降両用
–管理者だとtrueが、それ以外だとfalseが返る
on getUsersPrivileges(aUser)
  set aVer to system attribute "sys2" –OSメジャーバージョンを取得する(例:Mac OS X 10.6.4→6)
  
  
set current_user to aUser
  
  
if aVer > 4 then
    –Mac OS X 10.5以降の処理
    
set adR to (do shell script "/usr/bin/dsmemberutil checkmembership -U " & current_user & " -G admin users")
    
    
if adR = "user is a member of the group" then
      return true
    else
      return false
    end if
    
  else
    –Mac OS X 10.4までの処理
    
set admin_users to (do shell script "/usr/bin/niutil -readprop . /groups/admin users")
    
tell (a reference to AppleScript’s text item delimiters)
      set {old_atid, contents} to {contents, " "}
      
set {admin_users, contents} to {text items of admin_users, old_atid}
    end tell
    
    
if current_user is in admin_users then
      return true
    else
      return false
    end if
  end if
  
end getUsersPrivileges

–数値にゼロパディングしたテキストを返す
on retZeroPaddingText(aNum, aLen)
  set tText to ("00000000" & aNum as text)
  
set tCount to length of tText
  
set resText to text (tCount – aLen + 1) thru -1 of tText
  
return resText
end retZeroPaddingText

–Make a GMT Date Object with parameters from a given time zone.
on getDateInternational(aYear, aMonth, aDay, anHour, aMinute, aSecond, timeZoneAbbreviation)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
theNSCalendar’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithAbbreviation:(timeZoneAbbreviation))
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:anHour minute:aMinute |second|:aSecond nanosecond:0
  
return theDate as date
end getDateInternational

★Click Here to Open This Script 

Posted in Calendar System | Tagged 10.11savvy 10.12savvy | Leave a comment

Safariで表示中のWebページの最終更新日時を取得

Posted on 8月 17, 2018 by Takaaki Naganoya

指定のWebページ(URL)の最終更新日時(Last Modified Date)を取得するAppleScriptです。

AppleScriptそのものにWebの最終更新日時を取得する関数や機能はありません。はい、おしまい。

……というのでは、AppleScriptの本質がぜんぜん分かっていないね、ということになります。AppleScriptは「それができるアプリケーション」(など)に依頼を出すのが処理スタイルだからです。

まずは、Safariにコマンドを投げて実行するスタイル。

AppleScript名:Safariのdo javascriptコマンドで最終更新日時を取得
— Created 2018-08-17 by Takaaki Naganoya
— 2018 Piyomaru Software
tell application "Safari"
  tell front document
    set dRes to (do JavaScript "document.lastModified;")
  end tell
end tell

★Click Here to Open This Script 

だいたいは、これで手を打つでしょう。ただし、最近のmacOSではセキュリティ強化のためにSafariのdo javascriptコマンドがデフォルトでは禁止されているので、Safariで「開発」メニューを表示させたあとに、「開発」メニューの「AppleEventからのJavaScriptを許可」「スマート検索フィールドからのJavaScriptを許可」を実行しておく必要があります(→ 書籍「AppleScript 10大最新技術」P-84)。

Mac AppStore上で配布/販売するアプリケーションの中で処理することを考えると、SafariをコントロールすることをInfo.plist内で宣言しておけばとくに問題はありません。

do javascriptコマンドの実行で一般的にはファイナルアンサーなのですが、なぜでしょう。リアルタイム日付が返ってくるパターンが多いです。

次は、shellのcurlコマンドを呼び出すスタイルです。指定URLのレスポンスヘッダーを出力させられるので、これを検索して出力します。ただ、YouTubeをはじめとするWebサイトでこの最終更新日を返してこないので、これでもダメな時はダメです。

AppleScript名:curlコマンドで最終更新日時を取得
— Created 2018-08-17 by Takaaki Naganoya
— 2018 Piyomaru Software
tell application "Safari"
  tell front document
    set aURL to URL
  end tell
end tell

try
  set uRes to (do shell script "curl -D – -s -o /dev/null " & aURL & " | grep Date:")
on error
  return false
end try

★Click Here to Open This Script 

これも現在日時を返してくるパターンが多いですね。また、噂レベルではあるものの「do shell scriptコマンドは極力使わないほうがいいよ」というお達しがScripter界隈で流れているので、将来的に何かがあるのかもしれません(昔の、ごくごく初期のMac OS XはBSDレイヤーというかBSDコマンド類が、OSインストール時にオプション扱いだったので、そういう未来はあるかもしれない)。

Mac AppStore上で配布/販売するアプリケーションの中で処理するのも、とくに問題はないのですが、今度はネットワーク接続することをあらかじめ宣言しておくのと、httpによる通信を行うことを宣言しておかないとネットワーク接続ができません。

最後の手段。Cocoaを呼び出して自前でWebのレスポンスヘッダーを取得するスタイル。

AppleScript名:Cocoaの機能で最終更新日時を取得
— Created 2018-08-17 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSString : a reference to current application’s NSString
property NSLocale : a reference to current application’s NSLocale
property NSURLRequest : a reference to current application’s NSURLRequest
property NSDateFormatter : a reference to current application’s NSDateFormatter
property NSURLConnection : a reference to current application’s NSURLConnection
property NSURLRequestUseProtocolCachePolicy : a reference to current application’s NSURLRequestUseProtocolCachePolicy

tell application "Safari"
  tell front document
    set aURL to URL
  end tell
end tell

set aURL to (current application’s |NSURL|’s URLWithString:aURL)
set {exRes, headerRes, aData} to checkURLResourceExistence(aURL, 3) of me
set aDate to headerRes’s |date| as string

set lastUpdateDate to dateFromStringWithDateFormat(aDate, "EEE, dd MMM yyyy HH:mm:ss zzz") of me
return lastUpdateDate

— 指定URLにファイル(画像など)が存在するかチェック
–> {存在確認結果(boolean), レスポンスヘッダー(NSDictionary), データ(NSData)}
on checkURLResourceExistence(aURL, timeOutSec as real)
  set aRequest to (NSURLRequest’s requestWithURL:aURL cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:timeOutSec)
  
set aRes to (NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value))
  
set dRes to (first item of (aRes as list))
  
set bRes to (second item of (aRes as list))
  
if bRes is not equal to missing value then
    set hRes to (bRes’s allHeaderFields())
    
set aResCode to (bRes’s statusCode()) as integer
  else
    set hRes to {}
    
set aResCode to -1 –error
  end if
  
return {(aResCode = 200), hRes, dRes}
end checkURLResourceExistence

–指定形式の日付テキストをAppleScriptのdateオブジェクトに変換
on dateFromStringWithDateFormat(dateString, dateFormat)
  set dStr to NSString’s stringWithString:dateString
  
set dateFormatStr to NSString’s stringWithString:dateFormat
  
  
set aDateFormatter to NSDateFormatter’s alloc()’s init()
  
aDateFormatter’s setDateFormat:dateFormatStr
  
aDateFormatter’s setLocale:(NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
  
  
set aDestDate to (aDateFormatter’s dateFromString:dStr)
  
  
return aDestDate as date
end dateFromStringWithDateFormat

★Click Here to Open This Script 

結果は3つとも変わりませんでした。Cocoa呼び出しするものも、作り置きしておいたサブルーチンを使いまわしただけなので、作るのに3分もかかっていません。

curlを呼び出すスタイル同様、Mac AppStore上で配布/販売するアプリケーションの中で処理するのもとくに問題はないのですが、httpによる通信を行うことを宣言しておかないとネットワーク接続ができません。

Safariでdo javascriptコマンドを実行するものは、最初にdo javascriptコマンドを実行する設定が必要。curlコマンドはまあそんなもんだろうかと。Cocoaの機能を呼び出す方法は、ここまでやってダメならあきらめがつくというところでしょうか。

Posted in Calendar Internet JavaScript URL | Tagged 10.11savvy 10.12savvy 10.13savvy NSDateFormatter NSLocale NSString NSURLConnection NSURLRequest Safari | Leave a comment

CotEditorの最前面のテキストの日付フォーマットを変換する

Posted on 7月 7, 2018 by Takaaki Naganoya

CotEditorでオープン中の最前面の書類中のテキストの、日付フォーマットを変換するAppleScriptです。


▲スクリーンショットは作成中のものです

Blogのアーカイブ本のオマケとして(記事だけだとウンザリする仕上がりだったので)、冒頭にその年に何があったかをAppleのニュースリリースから抽出して掲載してみたのですが、日付の形式が独特だったので、手で打ち直していました。

繰り返して行うと面倒だったので、NSDataDetectorで自然言語テキスト(CotEditorの本文テキスト)から日付を自動検出して書き換えを試みたのですが、NSDataDetectorではこのサンプルのようなほんのちょっとだけ手の加わった日付テキストでは検出してくれませんでした。

一応、フォーマット自体は固定だったので、フォーマッターだけ指定すれば日付テキストとして認識し、常識的なYYYY/MM/DDの日付フォーマットに書き換えるようにしてみました。


▲日付フォーマット文字列の入力


▲日付フォーマット置換したテキスト(処理は一瞬)

ただし、日付フォーマットテキストが行で独立しているもの(添付スクリーンショットのように)を処理対象にしているので、あまり汎用性はなさそうです。

一般的には正規表現で指定することになるんでしょうけれど、その正規表現というかもともとの日付フォーマットを元のテキストから自動検出してくれることがベストだと思います。

なお、CotEditorに依存した処理はひとつもないので、JeditΩでもmiでもテキストエディットでもTextWranglerでもBBEditでも、対象にして処理することはかんたんです。クリップボードの内容に対して処理したほうがいいのかもしれません。

AppleScript名:CotEditorの最前面のテキストの日付フォーマットを変換する
— Created 2018-07-07 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5"
use framework "Foundation"
use scripting additions

property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSLocale : a reference to current application’s NSLocale
property NSDictionary : a reference to current application’s NSDictionary
property NSCountedSet : a reference to current application’s NSCountedSet
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSDateFormatter : a reference to current application’s NSDateFormatter

set tmpArray to NSMutableArray’s new()

–変換元(テキストから自動取得できるとよかったのに)
set dFfromStr to text returned of (display dialog "Input Date Format:(年=yyyy, 月=MM, 日=dd)" default answer "MM月 dd, yyyy")

–変換先
set dOutFormStr to "yyyy/MM/dd"

tell application "CotEditor"
  tell front document
    set aRes to contents of it
  end tell
  
  
set aList to paragraphs of aRes
end tell

repeat with i in aList
  set j to contents of i
  
set theDate to dateFromStringWithDateFormat(j, dFfromStr) of me
  
if theDate is not equal to missing value then
    set newDateStr to convDateObjToStrWithFormat(theDate, dOutFormStr) of me
    (
tmpArray’s addObject:newDateStr)
  else
    (tmpArray’s addObject:j)
  end if
end repeat

–NSArrayを指定デリミタをはさんでテキスト化
set tRes to tmpArray’s componentsJoinedByString:(return)
set ttRes to tRes as string

tell application "CotEditor"
  tell front document
    set (contents of it) to ttRes
  end tell
end tell

–日付文字列からdate objectを作成する
on dateFromStringWithDateFormat(dateString as string, dateFormat as string)
  set dStr to NSString’s stringWithString:dateString
  
set dateFormatStr to NSString’s stringWithString:dateFormat
  
  
set aDateFormatter to NSDateFormatter’s alloc()’s init()
  
aDateFormatter’s setDateFormat:dateFormatStr
  
aDateFormatter’s setLocale:(NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
  
  
set aDestDate to (aDateFormatter’s dateFromString:dStr)
  
  
return aDestDate as list of string or string
end dateFromStringWithDateFormat

–date objectから指定の日付文字列を作成する
on convDateObjToStrWithFormat(aDateO as date, aFormatStr as string)
  set aDF to NSDateFormatter’s alloc()’s init()
  
  
set aLoc to NSLocale’s currentLocale()
  
set aLocStr to (aLoc’s localeIdentifier()) as string
  
  
aDF’s setLocale:(NSLocale’s alloc()’s initWithLocaleIdentifier:aLocStr)
  
aDF’s setDateFormat:aFormatStr
  
set dRes to (aDF’s stringFromDate:aDateO) as string
  
return dRes
end convDateObjToStrWithFormat

★Click Here to Open This Script 

Posted in Calendar Text | Tagged 10.11savvy 10.12savvy 10.13savvy CotEditor NSArray NSCountedSet NSDateFormatter NSDictionary NSLocale NSMutableArray NSSortDescriptor NSString | Leave a comment

日付テキストを年単位で集計

Posted on 6月 29, 2018 by Takaaki Naganoya

yyyy-MM-dd HH:mm:ss形式の日付テキストをdateオブジェクトに変換して日付を年単位で集計するAppleScriptです。

Blog Archiveのデータベースのダンプテキストを読み取って、年別の投稿記事本数の集計を行うために作成しました(といっても、既存のルーチンを組み合わせただけです)。

AppleScript名:日付テキストを年単位で集計
— Created 2018-06-28 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSLocale : a reference to current application’s NSLocale
property NSDictionary : a reference to current application’s NSDictionary
property NSCountedSet : a reference to current application’s NSCountedSet
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSDateFormatter : a reference to current application’s NSDateFormatter

set aList to {"2006-06-27 02:38:52", "2008-03-09 19:08:05", "2008-03-09 19:29:29"}
set aRes to totalDateStrByYear(aList, "yyyy-MM-dd HH:mm:ss") of me
–> {{aCount:1, aKey:2006}, {aCount:2, aKey:2008}}

–日付テキストを年単位で集計
on totalDateStrByYear(aList, strFormat)
  set theCountedSet to NSCountedSet’s |set|()
  
set newArray to NSMutableArray’s new()
  
  
repeat with i in aList
    set postDate to dateFromStringWithDateFormat(i, strFormat) of me –日付テキストをDate Objectに変換
    
set yearStr to (year of postDate) –「年」の数字
    (
newArray’s addObject:yearStr)
  end repeat
  
  
set resArray to countItemsByItsAppearance(newArray) of me
  
set bList to sortRecListByLabel(resArray, "aKey", true) of me –昇順ソート
  
return bList
end totalDateStrByYear

–日付文字列からdate objectを作成する
on dateFromStringWithDateFormat(dateString, dateFormat)
  set dStr to NSString’s stringWithString:dateString
  
set dateFormatStr to NSString’s stringWithString:dateFormat
  
  
set aDateFormatter to NSDateFormatter’s alloc()’s init()
  
aDateFormatter’s setDateFormat:dateFormatStr
  
aDateFormatter’s setLocale:(NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
  
  
set aDestDate to (aDateFormatter’s dateFromString:dStr)
  
  
return aDestDate as list of string or string
end dateFromStringWithDateFormat

–登場頻度でリストを集計する
on countItemsByItsAppearance(aList)
  set aSet to NSCountedSet’s alloc()’s initWithArray:aList
  
set bArray to NSMutableArray’s array()
  
set theEnumerator to aSet’s objectEnumerator()
  
  
repeat
    set aValue to theEnumerator’s nextObject()
    
if aValue is missing value then exit repeat
    
bArray’s addObject:(NSDictionary’s dictionaryWithObjects:{aValue, (aSet’s countForObject:aValue)} forKeys:{"aKey", "aCount"})
  end repeat
  
  
return bArray
end countItemsByItsAppearance

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as string, ascendF as boolean)
  set aArray to NSArray’s arrayWithArray:aRecList
  
  
set sortDesc to NSSortDescriptor’s alloc()’s initWithKey:aLabelStr ascending:ascendF
  
set sortDescArray to NSArray’s arrayWithObjects:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
  
set bList to (sortedArray) as list of string or string
  
return bList
end sortRecListByLabel

★Click Here to Open This Script 

Posted in Calendar list | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定の画像からEXIFの撮影日付(DateTimeOriginal)を取得 v2

Posted on 5月 31, 2018 by Takaaki Naganoya

指定の画像からEXIF情報を取得し、撮影日付(DateTimeOriginal)を取得するAppleScriptです。

Image Eventsで取得するよりも、BridgePlusで取得するほうが高速だったので差し替えてみました。

AppleScript名:指定の画像からEXIFの撮影日付(DateTimeOriginal)を取得 v2
— Created 2014-12-14 by Takaaki Naganoya
— 2014 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use BPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

property NSString : a reference to current application’s NSString
property NSLocale : a reference to current application’s NSLocale
property SMSForder : a reference to current application’s SMSForder
property NSDateFormatter : a reference to current application’s NSDateFormatter

set aTargFile to choose file of type {"public.image"}
set exifRes to readExifDateTimeOriginal(aTargFile) of me

–指定ファイルからのExifデータを取得し撮影日付を取得する
on readExifDateTimeOriginal(aTargFileAlias)
  set theMetadata to readMetadataFrom(aTargFileAlias) of me
  
set keysList to theMetadata’s allKeys()
  
  
if "{Exif}" is not in (keysList as list) then return false
  
  
set exifDate to theMetadata’s valueForKeyPath:"{Exif}.DateTimeOriginal"
  
if exifDate = missing value then return false
  
  
set fullDate to dateFromStringWithDateFormat(exifDate, "yyyy:MM:dd HH:mm:ss") of me
  
  
return fullDate
end readExifDateTimeOriginal

–指定ファイルからのメタデータ読み込み
on readMetadataFrom(imageFile)
  load framework
  
set {theRecord, theError} to SMSForder’s metadataFromImage:imageFile |error|:(reference)
  
if theRecord = missing value then — there was a problem, so extract the error description
    error (theError’s localizedDescription() as text) — number (theError’s code())
  else
    return theRecord
  end if
end readMetadataFrom

–日付文字列を形式指定しつつdate objectに変換
on dateFromStringWithDateFormat(dateString, dateFormat)
  set dStr to NSString’s stringWithString:dateString
  
set dateFormatStr to NSString’s stringWithString:dateFormat
  
  
set aDateFormatter to NSDateFormatter’s alloc()’s init()
  
aDateFormatter’s setDateFormat:dateFormatStr
  
aDateFormatter’s setLocale:(NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
  
  
set aDestDate to (aDateFormatter’s dateFromString:dStr)
  
  
return aDestDate as list of string or string
end dateFromStringWithDateFormat

★Click Here to Open This Script 

Posted in Calendar exif file Image | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Geofenceを付けつつReminder項目を追加

Posted on 5月 5, 2018 by Takaaki Naganoya

Reminders.app(リマインダー)に新規リマインド項目を作成し、Geofenceを設定するAppleScriptです。

Reminders.appのAppleScript用語辞書にはGeofence作成機能は用意されていないため、Cocoaの機能を利用して追加しました。

Geofenceは、指定の緯度・経度のポイントから半径xxxメートルの円の中に入る場合に発生するアラーム(Enter Alarm)、脱出する場合に発生するアラーム(Leave Alarm)の2種類を設定できます。

Mac上のReminders.app上で登録したこのリマインド項目がiCloud経由でiPhoneにシンクロされ、iPhoneを持って当該期間中に指定場所に行って半径200メートルの円の中から出るとアラームが表示されることになります。

AppleScript名:Geofenceを付けつつReminder項目を追加
— Created 2014-12-08 by Shane Stanley
— Modified 2015-09-24 by Takaaki Naganoya –Geofence Alarm
— Modified 2015-09-24 by Shane Stanley –Fix the way to Create the geofence alarm
— Modified 2015-09-24 by Takaaki Naganoya –change and test for El Capitan’s Enum bridging
–Reference:
–http://stackoverflow.com/questions/26903847/add-location-to-ekevent-ios-calendar
–http://timhibbard.com/blog/2013/01/03/how-to-create-remove-and-manage-geofence-reminders-in-ios-programmatically-with-xcode/
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "EventKit"

property EKAlarm : a reference to current application’s EKAlarm
property CLLocation : a reference to current application’s CLLocation
property EKEventStore : a reference to current application’s EKEventStore
property EKStructuredLocation : a reference to current application’s EKStructuredLocation
property EKEntityMaskReminder : a reference to current application’s EKEntityMaskReminder
property EKAlarmProximityEnter : a reference to current application’s EKAlarmProximityEnter
property EKAlarmProximityLeave : a reference to current application’s EKAlarmProximityLeave

–Start Date
set dSt to "2018/06/01 00:00:00"
set dateO1 to date dSt

–End Date
set dSt2 to "2018/08/01 00:00:00"
set dateO2 to date dSt2

tell application "Reminders"
  if not (exists list "test") then
    make new list with properties {name:"test"}
  end if
  
  
tell list "test"
    set aReminder to (make new reminder with properties {name:"Test1", body:"New Reminder", due date:dateO2, remind me date:dateO1, priority:9}) –priority 1:高、5:中、9:低、0:なし
    
set anID to id of aReminder
    
–> "x-apple-reminder://XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  end tell
end tell

set theID to text 20 thru -1 of anID
my setLocationToLeaveForReminderID(35.745769, 139.675565, "Target Place", theID, 200)

–指定場所に到着した時に発動するGeofence Alarmを指定のリマインダーに登録する。Geofence半径指定つき(単位:メートル)
on setLocationToEnterForReminderID(aLatitude, aLongitude, aTitle, theID, aRangeByMeter)
  — Get event store
  
set eventStore to EKEventStore’s alloc()’s initWithAccessToEntityTypes:(EKEntityMaskReminder)
  
  
— Get the reminder
  
set theReminder to eventStore’s calendarItemWithIdentifier:theID
  
  
–Create the geofence alarm
  
set enterAlarm to EKAlarm’s alarmWithRelativeOffset:0
  
enterAlarm’s setProximity:(EKAlarmProximityEnter)
  
set structLoc to EKStructuredLocation’s locationWithTitle:aTitle
  
set aLoc to CLLocation’s alloc()’s initWithLatitude:aLatitude longitude:aLongitude
  
structLoc’s setGeoLocation:aLoc
  
  
— Set radius by meters
  
structLoc’s setRadius:aRangeByMeter
  
enterAlarm’s setStructuredLocation:structLoc
  
  
theReminder’s addAlarm:enterAlarm
  
set aRes to eventStore’s saveReminder:theReminder commit:true |error|:(missing value)
  
  
return aRes as boolean
end setLocationToEnterForReminderID

–指定場所を出発した時に発動するGeofence Alarmを指定のリマインダーに登録する。Geofence半径指定つき(単位:メートル)
on setLocationToLeaveForReminderID(aLatitude, aLongitude, aTitle, theID, aRangeByMeter)
  — Get event store; 1 means reminders
  
set eventStore to EKEventStore’s alloc()’s initWithAccessToEntityTypes:(EKEntityMaskReminder)
  
  
— Get the reminder
  
set theReminder to eventStore’s calendarItemWithIdentifier:theID
  
  
–Create the geofence alarm
  
set leaveAlarm to EKAlarm’s alarmWithRelativeOffset:0
  
leaveAlarm’s setProximity:(EKAlarmProximityLeave)
  
set structLoc to EKStructuredLocation’s locationWithTitle:aTitle
  
set aLoc to CLLocation’s alloc()’s initWithLatitude:aLatitude longitude:aLongitude
  
structLoc’s setGeoLocation:aLoc
  
  
— Set radius by meters
  
structLoc’s setRadius:aRangeByMeter
  
leaveAlarm’s setStructuredLocation:structLoc
  
  
theReminder’s addAlarm:leaveAlarm
  
set aRes to eventStore’s saveReminder:theReminder commit:true |error|:(missing value)
  
  
return aRes as boolean
end setLocationToLeaveForReminderID

★Click Here to Open This Script 

Posted in Calendar geolocation | Tagged 10.11savvy 10.12savvy 10.13savvy Reminders | Leave a comment

旧暦計算を行う

Posted on 5月 4, 2018 by Takaaki Naganoya

指定の年・月・日から旧暦の日付および六曜を計算するAppleScriptです。

旧暦は太陰暦で、月の満ち欠けを基準とした暦(こよみ)です。旧暦計算は各種関数が必要になるため、AppleScriptだけで計算させると骨が折れますが、これまでにも他の言語のプログラムを呼び出すかたちで計算ライブラリを利用してきました。

本Scriptでは、Objective-Cで書かれたプログラム(バンドル内にplistでデータを持つタイプ)をCocoa Framework化してAppleScriptから呼び出せるようにしたものです。

–> kyurekiKit.framework (To ~/Library/Frameworks)

きょうび、旧暦計算が必要な用途なんてカレンダー製作とか手帳製作あたりで、クライアント企業もだいたい決まっています。業界にその名もとどろく、事前に仕様を出さないのに仕様後出しじゃんけんをしまくって難癖をつけてくる悪名高い極悪非道クライアント様が。だいたいは、事前に旧暦計算データも支給されるので、自前で旧暦計算する必要性に遭遇したことはありません。

AppleScript名:旧暦計算を行う
— Created 2018-05-04 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "KyurekiKit" –https://github.com/kyasusoft/Rokuyo
–2000年から2032年までのデータをFrameworkに内蔵

set curDat to current date
set curYear to year of curDat
set curMonth to month of curDat as number
set curDate to day of curDat

set r to current application’s KYRokuyo’s alloc()’s init()
set rokuyoText to (r’s sinrekiToRokuyoWithYear:curYear |month|:curMonth |day|:curDate) as string

set kyuMonth to (r’s kyuMonth) as integer
set kyuDay to (r’s kyuDay) as integer

return {kyuMonth, kyuDay, rokuyoText}
–>  {​​​​​3, ​​​​​19, ​​​​​"先負"​​​}

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

自然言語で指定した日時以降に作成されたファイルをSpotlight検索

Posted on 5月 3, 2018 by Takaaki Naganoya
AppleScript名:自然言語で指定した日時以降に作成されたファイルをSpotlight検索
— Created 2017-09-21 by Takaaki Naganoya
— Modified 2017-09-22 by Shane Stanley
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use mdLib : script "Metadata Lib" version "2.0.0"

property NSString : a reference to current application’s NSString
property NSDataDetector : a reference to current application’s NSDataDetector
property NSTextCheckingTypeDate : a reference to current application’s NSTextCheckingTypeDate

set aDate to getDatesIn("先週の月曜日") of me –"last Monday" in Japanese
log aDate

set thePath to POSIX path of (path to desktop)

set theFiles to mdLib’s searchFolders:{thePath} searchString:("kMDItemFSCreationDate >= %@") searchArgs:{aDate}
–> returns POSIX path list

on getDatesIn(aString)
  set anNSString to NSString’s stringWithString:aString
  
set theDetector to NSDataDetector’s dataDetectorWithTypes:(NSTextCheckingTypeDate) |error|:(missing value)
  
set theMatch to theDetector’s firstMatchInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
if theMatch = missing value then error "No date found with String:" & aString
  
set theDate to theMatch’s |date|()
  
return theDate as date
end getDatesIn

★Click Here to Open This Script 

Posted in Calendar file Spotlight | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

当日が1年の何週目かを求める

Posted on 4月 8, 2018 by Takaaki Naganoya
AppleScript名:当日が1年の何週目かを求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/04/08
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set a1Unit to (current application’s NSWeekOfYearCalendarUnit)
set a2Unit to (current application’s NSDayCalendarUnit)
set a3Unit to (current application’s NSMonthCalendarUnit)
set a4Unit to (current application’s NSYearCalendarUnit)

set aCalendar to current application’s NSCalendar’s currentCalendar()
set aComponent to aCalendar’s components:(a1Unit + a2Unit + a3Unit + a4Unit) fromDate:(current application’s NSDate’s |date|())
set aWN to aComponent’s weekOfYear()
–> 15

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

現時点における年齢を計算する

Posted on 4月 8, 2018 by Takaaki Naganoya
AppleScript名:現時点における年齢を計算する
— Created 2015-09-10 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–http://stackoverflow.com/questions/4463893/
–how-to-calculate-the-age-based-on-nsdate

set aBirthday to "2009-04-24 12:00:00" –誕生日

set aFormatter to current application’s NSDateFormatter’s alloc()’s init()
aFormatter’s setDateFormat:"yyyy-MM-dd HH:mm:ss"
aFormatter’s setTimeZone:(current application’s NSTimeZone’s timeZoneForSecondsFromGMT:0)
set aBirthdayDate to aFormatter’s dateFromString:aBirthday

set currentDate to current application’s NSDate’s |date|()
set ageComponents to current application’s NSCalendar’s currentCalendar()’s components:(current application’s NSCalendarUnitYear) fromDate:aBirthdayDate toDate:currentDate options:0
set myAge to ageComponents’s |year|()
–>  8

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定日における年齢を計算する

Posted on 4月 8, 2018 by Takaaki Naganoya
AppleScript名:指定日における年齢を計算する
— Created 2015-09-10 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–http://stackoverflow.com/questions/4463893/
–how-to-calculate-the-age-based-on-nsdate

set aBirthday to "2009-04-24 12:00:00" –誕生日

set aFormatter to current application’s NSDateFormatter’s alloc()’s init()
aFormatter’s setDateFormat:"yyyy-MM-dd HH:mm:ss"
aFormatter’s setTimeZone:(current application’s NSTimeZone’s timeZoneForSecondsFromGMT:0)
set aBirthdayDate to aFormatter’s dateFromString:aBirthday

set currentDate to getDateInternational(2018, 4, 1, 9, 59, 35, "JST") of me
set ageComponents to current application’s NSCalendar’s currentCalendar()’s components:(current application’s NSCalendarUnitYear) fromDate:aBirthdayDate toDate:currentDate options:0
set myAge to ageComponents’s |year|()
–>  8

–Make a GMT Date Object with parameters from a given time zone.
on getDateInternational(aYear, aMonth, aDay, anHour, aMinute, aSecond, timeZoneAbbreviation)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
theNSCalendar’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithAbbreviation:(timeZoneAbbreviation))
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:anHour minute:aMinute |second|:aSecond nanosecond:0
  
return theDate
end getDateInternational

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

パラメータを指定してdateオブジェクトを作成

Posted on 3月 30, 2018 by Takaaki Naganoya
AppleScript名:パラメータを指定してdateオブジェクトを作成
— Created 2017-09-22 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

set a to getDateInternational(2012, 2, 28) of me
–> date "2012年2月28日火曜日 0:00:00"

set b to getDateInternationalYMDhms(2012, 2, 28, 1, 2, 3) of me
–> date "2012年2月28日火曜日 1:02:03"

–現在のカレンダーで指定年月のdate objectを返す(年、月、日、時、分、秒)
on getDateInternationalYMDhms(aYear, aMonth, aDay, anHour, aMinute, aSecond)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:anHour minute:aMinute |second|:aSecond nanosecond:0
  
return theDate as date
end getDateInternationalYMDhms

–現在のカレンダーで指定年月のdate objectを返す(年、月、日)
on getDateInternational(aYear, aMonth, aDay)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:0 minute:0 |second|:0 nanosecond:0
  
return theDate as date
end getDateInternational

★Click Here to Open This Script 

Posted in Calendar Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

MMMM dd yyyyの文字列をdateに変換

Posted on 3月 30, 2018 by Takaaki Naganoya

基礎的なScriptです。文字列で形式を指定した日付文字列を認識してAppleScriptのdateオブジェクトに変換するAppleScriptです。

「as list of string or string」の行は「as anything」が解釈されて(macOS 10.13まで)このようになるわけですが、macOS 10.14からは「as anything」(スクリプトエディタ)、「as any」(Script Debugger)と解釈されます。

本プログラムであれば、「as date」と書いておくと問題がないでしょう。

AppleScript名:MMMM dd yyyyの文字列をdateに変換.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/03/23
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set tmpDate to "2014-09-14 15:45:00"
set tmpD1 to dateFromStringWithDateFormat(tmpDate, "yyyy-MM-dd HH:mm:ss") of me
–> date "2014年9月14日日曜日 15:45:00"

set tmpDate to "August 19, 2018 15:45:00"
set tmpD2 to dateFromStringWithDateFormat(tmpDate, "MMMM dd, yyyy HH:mm:ss") of me
–> date "2018年8月19日日曜日 15:45:00"

return {tmpD1, tmpD2}

on dateFromStringWithDateFormat(dateString, dateFormat)
  set dStr to current application’s NSString’s stringWithString:dateString
  
set dateFormatStr to current application’s NSString’s stringWithString:dateFormat
  
  
set aDateFormatter to current application’s NSDateFormatter’s alloc()’s init()
  
aDateFormatter’s setDateFormat:dateFormatStr
  
aDateFormatter’s setLocale:(current application’s NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
  
  
set aDestDate to (aDateFormatter’s dateFromString:dStr)
  
  
return aDestDate as list of string or string
end dateFromStringWithDateFormat

★Click Here to Open This Script 

Posted in Calendar Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Twitter APIの日付フォーマットをAppleScriptのdateに変換する

Posted on 3月 30, 2018 by Takaaki Naganoya

Twitter APIの日付フォーマットの文字列をAppleScriptのdateオブジェクトに変換するAppleScriptです。

TwitterのREST APIから返ってくる日付フォーマットの文字列を変換しようとしてハマったのでメモしておきました。

AppleScript名:Twitter APIの日付フォーマットをAppleScriptのdateに変換する.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/03/30
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions

property NSString : a reference to current application’s NSString
property NSLocale : a reference to current application’s NSLocale
property NSDateFormatter : a reference to current application’s NSDateFormatter

set a to "Fri Mar 30 11:03:57 +0000 2018"

set aDF to NSDateFormatter’s alloc()’s init()
aDF’s setDateFormat:"EEE MMM dd HH:mm:ss Z yyyy"
aDF’s setLocale:(NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
set aResDate to aDF’s dateFromString:a
set aDateO to aResDate as date
–> date "2018年3月30日金曜日 20:03:57"

★Click Here to Open This Script 

Posted in Calendar Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

日の出、日没時刻を計算するv2

Posted on 2月 24, 2018 by Takaaki Naganoya

EDSunriseSetを用いて、指定の位置における日の出、日没時間を計算するAppleScriptです。

–> EDSunriseSet.framework(~/Library/Frameworks)

AppleScript名:日の出、日没時刻を計算するv2
— Created 2017-06-19 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "EDSunriseSet" –https://github.com/erndev/EDSunriseSet

set cityRecList to {{kCityName:"Tokyo", kCityLatitude:(35.6894875), kCityLongitude:(139.6917064), kCityTimeZone:"Asia/Tokyo"}}

set dList to {}

repeat with i in cityRecList
  set the end of dList to getSunriseSunset(i) of me
end repeat
return dList
–>  {​​​​​{​​​​​​​sunrise:date "2017年6月21日水曜日 4:25:37", ​​​​​​​sunset:date "2017年6月21日水曜日 19:00:21", ​​​​​​​civilTwilightStart:date "2017年6月21日水曜日 3:55:35", ​​​​​​​civilTwilightEnd:date "2017年6月21日水曜日 19:30:23", ​​​​​​​nauticalTwilightStart:date "2017年6月21日水曜日 3:18:15", ​​​​​​​nauticalTwilightEnd:date "2017年6月21日水曜日 20:07:44", ​​​​​​​astronomicalTwilightStart:date "2017年6月21日水曜日 2:36:45", ​​​​​​​astronomicalTwilightEnd:date "2017年6月21日水曜日 20:49:13", ​​​​​​​cityname:"Tokyo"​​​​​}​​​}

on getSunriseSunset(cityRec)
  set curLocale to current application’s NSLocale’s currentLocale()
  
set curDate to current application’s NSDate’s |date|()
  
  
set aTZ to current application’s NSTimeZone’s alloc()’s initWithName:(kCityName of cityRec)
  
set aSunrizeSunset to current application’s EDSunriseSet’s alloc()’s initWithDate:curDate timezone:aTZ latitude:(kCityLatitude of cityRec) longitude:(kCityLongitude of cityRec)
  
  
–日の出、日没  
  
set aSunRiseDate to (aSunrizeSunset’s sunrise) as date
  
set aSunSetDate to (aSunrizeSunset’s sunset) as date
  
  
–https://en.wikipedia.org/wiki/Twilight
  
–https://ja.wikipedia.org/wiki/薄明
  
  
–市民薄明(常用薄明、第三薄明)
  
set aCivilTwilightStart to (aSunrizeSunset’s civilTwilightStart) as date
  
set aCivilTwilightEnd to (aSunrizeSunset’s civilTwilightEnd) as date
  
  
–航海薄明(第二薄明)
  
set aNauticalTwilightStart to (aSunrizeSunset’s nauticalTwilightStart) as date
  
set aNauticalTwilightEnd to (aSunrizeSunset’s nauticalTwilightEnd) as date
  
  
–天文薄明(第一薄明)
  
set anAstronomicalTwilightStart to (aSunrizeSunset’s astronomicalTwilightStart) as date
  
set anAstronomicalTwilightEnd to (aSunrizeSunset’s astronomicalTwilightEnd) as date
  
  
return {sunrise:aSunRiseDate, sunset:aSunSetDate, civilTwilightStart:aCivilTwilightStart, civilTwilightEnd:aCivilTwilightEnd, nauticalTwilightStart:aNauticalTwilightStart, nauticalTwilightEnd:aNauticalTwilightEnd, astronomicalTwilightStart:anAstronomicalTwilightStart, astronomicalTwilightEnd:anAstronomicalTwilightEnd, cityname:kCityName of cityRec}
end getSunriseSunset

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

2つの日付の期間を日本語表記でていねいに返す

Posted on 2月 24, 2018 by Takaaki Naganoya
AppleScript名:2つの日付の期間を日本語表記でていねいに返す
— Created 2016-01-17 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–Date Difference
set sDate to "2016/1/15" –Japanese Date format "YYYY/MM/DD"
set eDate to "2016/1/20" –Japanese Date format "YYYY/MM/DD"
set aDiffStr to retDateDiffStr(sDate, eDate, "/", "/", "", "〜") of me
–> "2016/1/15〜20"

–Month Difference
set sDate to "2016/1/15" –Japanese Date format "YYYY/MM/DD"
set eDate to "2016/2/20" –Japanese Date format "YYYY/MM/DD"
set bDiffStr to retDateDiffStr(sDate, eDate, "年", "月", "日", "〜") of me
–> "2016年1月15日〜2月20日"

–Year Difference
set sDate to "2015/12/15" –Japanese Date format "YYYY/MM/DD"
set eDate to "2016/1/20" –Japanese Date format "YYYY/MM/DD"
set bDiffStr to retDateDiffStr(sDate, eDate, "年", "月", "日", "〜") of me
–> "2015年12月15日〜2016年1月20日"

–2つの日付の期間を日本語表記でていねいに返す
on retDateDiffStr(sDate, eDate, ySeparator, mSeparator, dSeparator, diffSeparator)
  
  
set sDateO to date sDate
  
set eDateO to date eDate
  
  
set diffY to (year of eDateO) – (year of sDateO)
  
set diffM to (month of eDateO) – (month of sDateO)
  
set diffD to (day of eDateO) – (day of sDateO)
  
  
set sYstr to (year of sDateO) as string
  
set sMstr to (month of sDateO as number) as string
  
set sDstr to (day of sDateO) as string
  
  
set eYstr to (year of eDateO) as string
  
set eMstr to (month of eDateO as number) as string
  
set eDstr to (day of eDateO) as string
  
  
if diffY > 0 then
    –Year Difference
    
set outStr to sYstr & ySeparator & sMstr & mSeparator & sDstr & dSeparator & diffSeparator & eYstr & ySeparator & eMstr & mSeparator & eDstr & dSeparator
  else if diffM > 0 then
    –Month Difference
    
set outStr to sYstr & ySeparator & sMstr & mSeparator & sDstr & dSeparator & diffSeparator & eMstr & mSeparator & eDstr & dSeparator
  else if diffD > 0 then
    –Date Difference
    
set outStr to sYstr & ySeparator & sMstr & mSeparator & sDstr & diffSeparator & eDstr & dSeparator
  end if
  
  
return outStr
  
end retDateDiffStr

★Click Here to Open This Script 

Posted in Calendar | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • CotEditorで2つの書類の行単位での差分検出
  • macOS 15, Sequoia
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Adobe AcrobatをAppleScriptから操作してPDF圧縮
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • AppleScriptによる並列処理
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • Keynote/Pagesで選択中の表カラムの幅を均等割
  • Keynote、Pages、Numbers Ver.14.0が登場
  • macOS 15 リモートApple Eventsにバグ?
  • デフォルトインストールされたフォント名を取得するAppleScript

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1392) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (190) 14.0savvy (142) 15.0savvy (120) CotEditor (66) Finder (51) iTunes (19) Keynote (116) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (54) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2025年3月
  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC