Date Extension functions for iOS swift
The below are the extension functions that will be used for our app to extend the default functionality of the date datatyoe.
extension Date {
//It can be used for get the first date of the month
func startOfMonth() -> Date {
var start = self.addDays(daysToAdd: -self.getDay())
start = start.addDays(daysToAdd: 1)
return start
}
//It can be used for get the end date of the month
func endOfMonth() -> Date {
return Calendar.current.date(byAdding
}
//It can be used for get the first date of the week
var startOfWeek: Date {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yea
return gregorian.date(byAdding: .day, value: 1, to: sunday) ?? Date()
}
//It can be used for get the last date of the week
var endOfWeek: Date {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yea
return gregorian.date(byAdding: .day, value: 7, to: sunday) ?? Date()
}
//It can be used to get the local date based on the device location
func localDate() -> Date {
let timeZoneOffset = Double(TimeZone.current.second
guard let localDate = Calendar.current.date(byAdding
return localDate
}
//It can be used for get the name of the day for the date
func getDayName() -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.local
dateFormatter.dateFormat = "EEEE" // "EE" to get short style
let dayInWeek = dateFormatter.string(from: self) // "Sunday"
return dayInWeek
}
func dayOfWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormats.dayOnly
return dateFormatter.string(from: self).capitalized
// or use capitalized(with: locale) if you want
}
//It can be used for get time ago like 1 hour ago or 10 mins ago or 2days ago
func timeAgoDisplay() -> String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
return formatter.localizedString(for: self, relativeTo: Date())
}
func isEqual(to date: Date, toGranularity component: Calendar.Component, in calendar: Calendar = .current) -> Bool {
calendar.isDate(self, equalTo: date, toGranularity: component)
}
func isInSameMonth(as date: Date) -> Bool { isEqual(to: date, toGranularity: .month) }
// MARK: - Get date is first day of month
func isFirstDayOfMonth() -> Bool {
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.day, from: self)
let dayOfMonth = components.day
switch dayOfMonth {
case 1:
return true
default:
return false
}
}
// MARK: - Get month Name
func getMonthName() -> String {
let format = DateFormatter()
format.dateFormat = dateFormats.monthName
return format.string(from: self)
}
func daySuffix() -> String {
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.day, from: self)
let dayOfMonth = components.day
switch dayOfMonth {
case 1, 21, 31:
return "st"
case 2, 22:
return "nd"
case 3, 23:
return "rd"
default:
return "th"
}
}
func getDateTime(date:Date) -> String {
let format = DateFormatter()
format.timeZone = NSTimeZone.local
format.dateFormat = dateFormats.dateMonthSec
return format.string(from: date)
}
func isToday() -> Bool {
return Calendar.current.isDateInToday
}
func isToday(datefrom:Date,dateTo:D
return Calendar.current.isDate(
}
func isYesterday(datefrom:Date,date
return Date().isToday(datefrom: datefrom.addDays(daysToAdd: -1), dateTo: dateTo)
}
func getTime(date:Date) -> String {
let format = DateFormatter()
format.timeZone = NSTimeZone.local
format.dateFormat = dateFormats.hourMinSec
return format.string(from: date)
}
enum SearchDirection {
case Next
case Previous
var calendarSearchDirection: Calendar.SearchDirection {
switch self {
case .Next:
return .forward
case .Previous:
return .backward
}
}
}
func getWeekDaysInEnglish() -> [String] {
var calendar = Calendar(identifier: .gregorian)
calendar.locale = Locale(identifier: "en_US_POSIX")
return calendar.weekdaySymbols
}
func get(_ direction: SearchDirection,
_ weekDay: Weekday,
considerToday consider: Bool = false) -> Date {
let dayName = weekDay.rawValue
let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() }
assert(weekdaysName.contains(
let searchWeekdayIndex = weekdaysName.firstIndex(of: dayName)! + 1
let calendar = Calendar(identifier: .gregorian)
if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex {
return self
}
var nextDateComponent = DateComponents()
nextDateComponent.weekday = searchWeekdayIndex
let date = calendar.nextDate(after: self,
matching: nextDateComponent,
matchingPolicy: .nextTime,
direction: direction.calendarSearchDirect
return date!
}
func next(_ weekday: Weekday, considerToday: Bool = false) -> Date {
return get(.Next,
weekday,
considerToday: considerToday)
}
func previous(_ weekday: Weekday, considerToday: Bool = false) -> Date {
return get(.Previous,
weekday,
considerToday: considerToday)
}
func addminutes(minsToAdd: Int) -> Date {
let secondsInHours: TimeInterval = Double(minsToAdd) * 60
let dateWithHoursAdded: Date = self.addingTimeInterval(
//Return Result
return dateWithHoursAdded
}
func weeksOfTheYear(fromdate: Date) -> NSNumber {
return NSNumber(value: Calendar.current.component(.we
}
func getDay() ->Int {
let calendar = Calendar.current
let components = calendar.dateComponents([.year
let day = components.day
return day!
}
func getMonth() -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([.year
let month = components.month
return month!
}
func getYear() -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([.year
let month = components.month
return month!
}
enum Weekday: String {
case monday, tuesday, wednesday, thursday, friday, saturday, sunday
}
func addDays(daysToAdd: Int) -> Date {
let secondsInDays: TimeInterval = Double(daysToAdd) * 60 * 60 * 24
let dateWithDaysAdded: Date = self.addingTimeInterval(
//Return Result
return dateWithDaysAdded
}
func rounded(minutes: TimeInterval, rounding: DateRoundingType = .round) -> Date {
return rounded(seconds: minutes * 60, rounding: rounding)
}
func rounded(seconds: TimeInterval, rounding: DateRoundingType = .round) -> Date {
var roundedInterval: TimeInterval = 0
switch rounding {
case .round:
roundedInterval = (timeIntervalSinceReferenceDat
case .ceil:
roundedInterval = ceil(timeIntervalSinceReferenc
case .floor:
roundedInterval = floor(timeIntervalSinceReferen
}
return Date(timeIntervalSinceReferenc
}
func startDayOfDate() -> Date {
return Calendar.current.date(bySettin
}
func endDayOfDate() -> Date {
return Calendar.current.date(bySettin
}
}
Comments
Post a Comment