Tuesday, August 20, 2019

#1 2019-08-04 11:20:06 pm

davidhmorgan
Member
From:: Sydney
Registered: 2014-08-20
Posts: 68

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.

Applescript:


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


Filed under: dates, Date String, Obj C

Offline

 

#2 2019-08-04 11:44:32 pm

Shane Stanley
Member
From:: Australia
Registered: 2002-12-07
Posts: 5825

Re: Repurposing the NS Date Formatter

davidhmorgan wrote:

it always sets it to January



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


Shane Stanley <sstanley@myriad-com.com.au>
www.macosxautomation.com/applescript/apps/
latenightsw.com

Offline

 

#3 2019-08-05 12:33:24 am

davidhmorgan
Member
From:: Sydney
Registered: 2014-08-20
Posts: 68

Re: Repurposing the NS Date Formatter

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

Offline

 

#4 2019-08-05 12:55:09 am

Shane Stanley
Member
From:: Australia
Registered: 2002-12-07
Posts: 5825

Re: Repurposing the NS Date Formatter


Shane Stanley <sstanley@myriad-com.com.au>
www.macosxautomation.com/applescript/apps/
latenightsw.com

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)