Repurposing the NS Date Formatter

Hi all,

I’ve tried repurposing Shane’s code from here: https://macscripter.net/viewtopic.php?id=45195

into a general purpose date formatter, like the following but it’s not working consistently. Some date strings and formats work OK but when I change it to a new format, it doesn’t work; then when I change it back, it still doesn’t work! What am I missing here? Every time I’ve tried, it always gets the year and day right but never the month; it always sets it to January.


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

--FOR REFERENCE
--set DateFormats to {"yyyy_MMMM_DD", "yy_MMMM_DD", "MMMM_DD_yyyy", "MMMM_DD_yy"}
--set DateStrings to {"1986_August_27", "86_August_27", "August_27_1986", "August_27_86"}

set ThisString to "23_August_2019"
set ThisFormat to "DD_MMMM_yyyy"
set ThisDate to my HHmmFromRFC3339(ThisString, ThisFormat)

on HHmmFromRFC3339(ThisString, ThisFormat)
	set df to current application's NSDateFormatter's new()
	df's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"en_US_POSIX")
	df's setDateFormat:ThisFormat
	df's setTimeZone:(current application's NSTimeZone's timeZoneForSecondsFromGMT:0)
	set theDate to df's dateFromString:ThisString
	try
		return theDate as date
	on error
		return missing value
	end try
end HHmmFromRFC3339

That’s because you’re using DD, which means day of the year. Use dd instead.

Brilliant! Thanks for that, I thought it might be something simple. I should have read this reference a bit closer: https://nsdateformatter.com/

This is a bit more detailed:

https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table