Skip to content

Instantly share code, notes, and snippets.

@junebash
Created May 9, 2021 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junebash/07b392ffe1d0cadc228bec0e5ef4ce34 to your computer and use it in GitHub Desktop.
Save junebash/07b392ffe1d0cadc228bec0e5ef4ce34 to your computer and use it in GitHub Desktop.
Print formatted week in Markdown
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())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment