Skip to content

Instantly share code, notes, and snippets.

@GE-N
Created October 31, 2018 08:40
Show Gist options
  • Save GE-N/74627a2d6a6f9844eaeb501bfb188d28 to your computer and use it in GitHub Desktop.
Save GE-N/74627a2d6a6f9844eaeb501bfb188d28 to your computer and use it in GitHub Desktop.
Calendar method; Get first monday and first day of year helper
import Foundation
extension Calendar {
static func australia() -> Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(abbreviation: "UTC")!
calendar.locale = Locale(identifier: "en_AU")
return calendar
}
/// Get a monday of current week.
///
/// - Parameter date: A date of week you need to get Monday. It's an optional parameter and default set as today.
///
/// - Returns: A date object of Monday for current week or nil if cannot get a first date from calendar.
///
/// Notes: reference https://stackoverflow.com/a/27044983/150768.
func firstMonday(inAWeekOf date: Date = Date()) -> Date? {
var dateComps = dateComponents([.weekOfYear, .year, .month, .weekday], from: date)
dateComps.weekday = 2
return self.date(from: dateComps)
}
/// Get a first day of current year.
///
/// - Parameter date: A date of year you need to get first day. It's an optional parameter and default set as today
///
/// - Returns: A date object at 1 Jan of current year or nil if cannot get a first date from calendar.
func firstDayOfYear(inAYearOf date: Date = Date()) -> Date? {
var dateComps = dateComponents([.weekdayOrdinal, .year, .month, .day], from: date)
dateComps.month = 1
dateComps.day = 1
return self.date(from: dateComps)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment