Last active
December 7, 2019 21:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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