How to make a date from year, month and day

There are 100s of hlep topics on how to set a date from a string. But I don’t like that because, well, locales could mess this up.

I have the day, month and year and want to turn that into a date object that I can use for scripting

So, how do I efficiently construct a date from the numbered values instead of from a formatted string?

I think this was originally written by Nigel:

tell (current date) to set {theASDate, year, day, its month, day, time} to {it, 2019, 1, 5, 9, 0}
return theASDate

Hey Shane,

why is “day” repeated twice, and why “month” has “its”?


Hi ldicroce.

The ‘day’ is firstly set here to a day (1) which occurs in every month, in order to avoid a possible overflow when the values in the date object are changed. For instance, if the script’s run on 31st May and you want to set a date which is, say, 19th February, setting the current date’s month to February gives a date which is effectively 31st February. Since February only has 28 days (or 29 in leap years), the date overflows and becomes the 3rd (or 2nd) March. Setting the day then to 19 gives 19th March instead of 19th February. There are similar possibilities when the day’s changed before the month. The way to avoid this is to set the day to 28 or less first (1 causes the least confusion) so that the month overflow can’t occur.

The keyword ‘month’ can refer to both a class and a property of a date. Placing ‘its’ in front of it here tells the compiler that it’s not a class but a property (of the result of ‘current date’). It’s OK to put ‘its’ in front of the other date properties too, but since the ones used here are only properties, there’s no danger of the compiler mistaking them for classes and ‘its’ can be left out.

Edit: ‘hours’, ‘minutes’, and ‘seconds’ also need ‘its’ when they’re set with this method. Otherwise ‘hours’ and ‘minutes’ are the smiliarly named applescript constants and ‘seconds’ is a keyword associated with ‘timeout’ statements. I often use ‘its’ with all the terms now, just for visual consistency.

tell (current date) to set {theASDate, its day, its year, its month, its day, its time} to {it, 1, 2019, 2, 19, 0}

-- tell (current date) to set {theASDate, its day, its year, its month, its day, its hours, its minutes, its seconds} to {it, 1, 2019, 2, 19, 14, 10, 30}

return theASDate

Thanks !
Much appreciated !!!