Skip to content

Instantly share code, notes, and snippets.

@unferna
Last active December 7, 2019 21:17
Show Gist options
  • Save unferna/52f0c45fa33d8a880415b22b0a144383 to your computer and use it in GitHub Desktop.
Save unferna/52f0c45fa33d8a880415b22b0a144383 to your computer and use it in GitHub Desktop.
[Day in a week] gets a specific day in a week #Swift #Date
import Foundation
/**
Gets a specific day in a week of a given date
- parameters:
- dayNumber: One day of the week, being 1 for Sunday until 7 for Saturday
- of: Date to work
- format: Output format desired
*/
extension Date {
static func dayInWeek(dayNumber: Int, of givenDate: Date, format: String) -> String {
let calendar = Calendar.current
var comps = calendar.dateComponents([.weekOfYear, .yearForWeekOfYear], from: givenDate)
comps.weekday = dayNumber
let dayInWeek = calendar.date(from: comps)!
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.timeZone = TimeZone.current
return formatter.string(from: dayInWeek)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment