Skip to content

Instantly share code, notes, and snippets.

@junebash
Created May 9, 2021 17:09
Show Gist options
  • Select an option

  • Save junebash/07b392ffe1d0cadc228bec0e5ef4ce34 to your computer and use it in GitHub Desktop.

Select an option

Save junebash/07b392ffe1d0cadc228bec0e5ef4ce34 to your computer and use it in GitHub Desktop.

Revisions

  1. junebash created this gist May 9, 2021.
    52 changes: 52 additions & 0 deletions FormattedMarkdownWeek.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    import Foundation

    /// Prints the week in Markdown format. Useful for planning. Throw this into a TextExpander shell script!
    func markdownWeek() -> String {
    let cal = Calendar.current

    func weekDay(of date: Date) -> Int {
    cal.component(.weekday, from: date)
    }

    func nextDay(from date: Date, count: Int = 1) -> Date {
    cal.date(byAdding: .day, value: count, to: date)!
    }

    func formattedWeekOfYear(for date: Date) -> String {
    let week = cal.component(.weekOfYear, from: date)
    let year = cal.component(.yearForWeekOfYear, from: date)

    let weekFormatter = NumberFormatter()
    weekFormatter.minimumIntegerDigits = 2
    let formattedWeek = weekFormatter.string(from: week as NSNumber)!

    return "\(year)-W\(formattedWeek)"
    }

    let dayFormatter = DateFormatter()
    dayFormatter.dateFormat = "EEEE yyyy-MM-dd"

    func formattedDayEntry(for date: Date) -> String {
    let datePortion = dayFormatter.string(from: date)
    return "## \(datePortion)\n\n- "
    }

    func thisMonday() -> Date {
    var currentDate = Date()
    var currentWeekday = weekDay(of: currentDate)
    while currentWeekday != 2 { // 2 = monday
    currentDate = nextDay(from: currentDate)
    currentWeekday = weekDay(of: currentDate)
    }
    return currentDate
    }

    let monday = thisMonday()
    let dayComponents = (0...6)
    .map { nextDay(from: monday, count: $0) }
    .map(formattedDayEntry(for:))
    let components = ["# \(formattedWeekOfYear(for: monday))"] + dayComponents
    return components.joined(separator: "\n\n")
    }

    print(markdownWeek())