Search code examples
excelapplescript

Get last day in month in AppleScript and holidays in current month


I am writing an AppleScript which generates an MS Excel spreadsheet every month. I need to know how many days are in the current month, then go trough all months and decide if a given day is a weekday or a holiday.

I suppose I would save holidays (from this web http://kalendar365.cz/statni-svatky/2016 as table and access them locally) for this.

My question is:

  1. How do I get the last day in a month?
  2. How do I efficiently loop trough all days in the current month and decide if it is Sunday, Saturday or a day specified somewhere else (for example, in a text file of xlsx spreadsheet)?

Solution

  • pbell's answer is promising, but the GetLastDay function doesn't work correctly for months that have fewer than 31 days; here's a function that fixes that:

    # Returns the number of days in the month that the given date falls in.
    # Example:
    #     my GetNumberOfDaysInMonth(current date)
    on GetNumberOfDaysInMonth(aDate)
        local aDateCopy
        copy aDate to aDateCopy
        set day of aDateCopy to 1
        if month of aDateCopy is December then
            set year of aDateCopy to ((year of aDateCopy) + 1)
            set month of aDateCopy to 1
        else
            set month of aDateCopy to ((month of aDateCopy) + 1)
        end if
        return day of (aDateCopy - 1 * days)
    end GetNumberOfDaysInMonth
    

    The approach is based on setting the date to the 1st of the month, then incrementing the month (possibly rolling over into the next year), and subtracting 1 day, which works correctly with all dates, even in leap years.