Search code examples
iosswiftswift3nsdatenscalendar

Swift 3 - Android Equivalent Of Getting Past 12 Months Using Calendar Class


In Android, I'm able to generate labels for my line chart for the past 12 months including this month.

In my TimeDateHelper class:

public static DateFormat getMonthYearChartLabelFormat() {
    DateFormat monthYearChartLabelFormat = new SimpleDateFormat("MMM ''yy", Locale.US);
    monthYearChartLabelFormat.setTimeZone(TimeZone.getDefault());
    return monthYearChartLabelFormat;
}

In my other LineChartActivity class:

private void setUpMonthLabels() {
    this.labels = new ArrayList<>();
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getDefault());
    cal.add(Calendar.MONTH, -11);
    for (int i = 0; i < 12; i++) {
        this.labels.add(TimeDateHelper.getMonthYearChartLabelFormat().format(cal.getTime()));
        cal.add(Calendar.MONTH, 1);
    }
}

The enumerateDates method in Swift 3's Calendar class is way too confusing. I don't know whether to use that or something else. All I want is the past 12 months including this month. For example, this month is December, so the output would be:

Jan '16
Feb '16
Mar '16
Apr '16
May '16
Jun '16
Jul '16
Aug '16
Sep '16
Oct '16
Nov '16
Dec '16

How can I get this done with Swift 3?

**** PROGRESS ****

So far, I have some formatting set up:

let dateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.timeZone = TimeZone.current
    return formatter
}()

func getMonthYearChartLabelString(fromDate date: Date) -> String {
    dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMM ''yy", options: 0, locale: Locale(identifier: "en-US"))
    return dateFormatter.string(from: date)
}

The apostrophe doesn't work for some reason tho (ex. it shows Dec 16 when it should show Dec '16).


Solution

  • Here's my first stab at it.

    import Foundation
    
    var past12Months: [String] {
        let today = Date()
        let dates = (-12...0).flatMap{ Calendar.current.date(byAdding: .month, value: $0, to: today)}
    
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM ''yy"
    
        let strings = dates.map{ dateFormatter.string(from: $0)! } //TODO: add error handling here
        return strings
    }
    
    print(past12Months)