Convert months to numbers

I know I have seen this in my books, but I cannot find it now.

How do you convert a list of all months to numbers for use in a script?

IE January=01
February=02
etc.

When the script gets a (month of current date), it returns the value in the number format.

This may be a little verbose but it works:

Jon

There are many ways to do it. Here’s one that I don’t claim to be the best or most efficient.

set monthNumber to my getMonthNum(current date)

on getMonthNum(date_)
	set monthNames to "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
	set counter to 0
	set mth to text 1 thru 3 of ((month of date_) as string)
	repeat
		set counter to counter + 1
		if word counter of monthNames is mth then
			set monthNum to counter
			exit repeat
		end if
	end repeat
	return monthNum
end getMonthNum

– Rob

You may be interested in my discussion of “French Vanilla” in the Code Exchange section of this site:

http://macscripter.net/exchange/index.php?id=P119

Since posting that, I’ve come up with an “English Fudge” variant, which works with any AppleScript date, including those before 1904:

set theDate to (current date)

copy theDate to b
set b's month to January
set monthNum to (b - 2500000 - theDate) div -2500000

If you want a string with a leading zero where appropriate, you can add:

set monthNumStr to text 2 thru 3 of ((100 + monthNum) as string)

If you’re really in a hurry, you can mathematically combine the last two lines so that the whole process becomes:

copy theDate to b
set b's month to January
set monthNumStr to text 2 thru 3 of ((b - 252500000 - theDate) div -2500000) as string)

:slight_smile:

The above gets the month number directly from the date, which I think is what you wanted. However, if you just have a month whose number you want to know, you can convert it to a date first and get the number from that:

set myMonth to March

set theDate to date (myMonth as string) -- 1st of myMonth in current year

copy theDate to b
set b's month to January
set monthNumStr to text 2 thru 3 of (((b - 252500000 - theDate) div -2500000) as string)
--> "03"