Applescript date manipulation to get multiple formats

applescript

I need to get a date (month, day, year) in multiple different formats for each part. So, for January 2, 1999 I need:

  • the month as January and Jan and 01 and 1
  • the day as 2 and 02
  • the year as 1999 and 99

I'm currently doing it with this hodgepodge including a shell call to the date command as seen below. Clearly I do not know much about Applescript. Equally clearly, there has to be a more efficient (code-wise…performance isn't really an issue) way!

set {year:y, month:m, day:d} to (current date)
# aka 1999 - January - 2

set shortmonth to text 1 thru 3 of (month of (current date) as text)
# aka Jan

set nummonth to do shell script "date '+%m'"
# aka 01

set dd to text -2 thru -1 of ("00" & (day of (current date)))
# aka 02

set yy to text 3 thru 4 of (y as text)
# aka 99

Best Answer

 set theMonth to do shell script " date -v2d -v1m -v99y +%B%n%b%n%m%n%-m"

-> "January

Jan

01

1"

set theDay to do shell script " date -v2d -v1m -v99y +%A%n%a%n%d%n%-d"

-> "Saturday

Sat

02

2"

set theYear to do shell script " date -v2d -v1m -v99y +%Y%n%y"

-> "1999

99"

  • -v flag adjusts the date item without changing the real date.

  • -v2d is 2nd day

  • -v1m is first month

  • -v99y is the year 1999

    The date formatters are:

  • %n new line

  • %B full month name
  • %b abbr month name
  • %m month number with leading zero
  • %-m month number without leading zero

The other formatters follow the same way. You can find more format info by simply googling.

If you want to do it all in applescript then I suggest you read through MacScripter / Dates & Times in AppleScripts

---------- update

I do think it is more efficient doing it with the shell script. But if I was going to try and do it in Applescript alone. I would use handlers to either pad or shorten the item. And the just pass the month, year and day to them to sort.

set {year:y, month:m, day:d} to current date
--set m to m + 1

set theYearLong to y as string
set theYearShort to shorten(y)


set theMonthNumberZero to pad((m as integer) as string)
set theMonthNumber to ((m as integer) as string)
set theMonthLong to m as string
set theMonthShort to shorten(m)


set theDayNumberZero to pad((d as integer) as string)
set theDayNumber to ((d as integer) as string)



on pad(thisNumber)
    if length of thisNumber = 1 then
        return "0" & thisNumber
    else
        return thisNumber
    end if
end pad


on shorten(thisItem)

    if class of thisItem is integer then
        return characters 3 thru -1 of (thisItem as text) as string
    else
        return characters 1 thru 3 of (thisItem as text) as string
    end if
end shorten

There probably is a better way of doing it but this example may give you an idea..