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(byAddingDateComponents(month: 1, day: -1), toself.startOfMonth())!

    }


    //It can be used for get the first date of the week

    var startOfWeekDate {

        let gregorian = Calendar(identifier: .gregorian)

        guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], fromself)) else { return Date() }

        return gregorian.date(byAdding: .dayvalue: 1, to: sunday) ?? Date()

    }


    //It can be used for get the last date of the week

    var endOfWeekDate {

        let gregorian = Calendar(identifier: .gregorian)

        guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], fromself)) else { return Date() }

        return gregorian.date(byAdding: .dayvalue: 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.secondsFromGMT(forself))

        guard let localDate = Calendar.current.date(byAdding: .secondvalueInt(timeZoneOffset), toselfelse {return Date()}

        

        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(fromself// "Sunday"

        return dayInWeek

    }


    func dayOfWeek() -> String? {

        let dateFormatter = DateFormatter()

        dateFormatter.dateFormat = dateFormats.dayOnly

        return dateFormatter.string(fromself).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(forselfrelativeToDate())

    }


    

    func isEqual(to date: DatetoGranularity component: Calendar.Componentin calendar: Calendar = .current) -> Bool {

        calendar.isDate(selfequalTo: 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(.dayfromself)

        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(fromself)

    }

    

    func daySuffix() -> String {

        let calendar = Calendar.current

        let components = (calendar as NSCalendar).components(.dayfromself)

        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(self)

    }

    

    func isToday(datefrom:Date,dateTo:Date) -> Bool {

        return Calendar.current.isDate(datefrom, inSameDayAs: dateTo)

    }

    func isYesterday(datefrom:Date,dateTo:Date) -> Bool {

        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 calendarSearchDirectionCalendar.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(dayName), "weekday symbol should be in form \(weekdaysName)")

        let searchWeekdayIndex = weekdaysName.firstIndex(of: dayName)! + 1

        let calendar = Calendar(identifier: .gregorian)

        if consider && calendar.component(.weekdayfromself) == searchWeekdayIndex {

            return self

        }

        

        var nextDateComponent = DateComponents()

        nextDateComponent.weekday = searchWeekdayIndex

        let date = calendar.nextDate(afterself,

                                     matching: nextDateComponent,

                                     matchingPolicy: .nextTime,

                                     direction: direction.calendarSearchDirection)

        

        return date!

    }

    

    func next(_ weekday: WeekdayconsiderTodayBool = false) -> Date {

        return get(.Next,

                   weekday,

                   considerToday: considerToday)

    }

    

    func previous(_ weekday: WeekdayconsiderTodayBool = false) -> Date {

        return get(.Previous,

                   weekday,

                   considerToday: considerToday)

    }

    

    func addminutes(minsToAddInt) -> Date {

        let secondsInHours: TimeInterval = Double(minsToAdd) * 60

        let dateWithHoursAdded: Date = self.addingTimeInterval(secondsInHours)

        //Return Result

        return dateWithHoursAdded

    }


    func weeksOfTheYear(fromdateDate) -> NSNumber {

        return NSNumber(valueCalendar.current.component(.weekOfYearfrom:fromdate))

    }


    func getDay() ->Int {

        let calendar = Calendar.current

        let components = calendar.dateComponents([.year, .month, .day], fromself)

        let day = components.day

        return day!

    }

    

    func getMonth() -> Int {

        let calendar = Calendar.current

        let components = calendar.dateComponents([.year, .month, .day], fromself)

        let month =  components.month

        return month!

    }

    

    func getYear() -> Int {

        let calendar = Calendar.current

        let components = calendar.dateComponents([.year, .month, .day], fromself)

        let month = components.month

        return month!

    }

    

    enum WeekdayString {

        case mondaytuesdaywednesdaythursdayfridaysaturdaysunday

    }

    

    func addDays(daysToAddInt) -> Date {

        let secondsInDays: TimeInterval = Double(daysToAdd) * 60 * 60 * 24

        let dateWithDaysAdded: Date = self.addingTimeInterval(secondsInDays)

        //Return Result

        return dateWithDaysAdded

    }

    

    func rounded(minutesTimeIntervalroundingDateRoundingType = .round) -> Date {

        return rounded(seconds: minutes * 60, rounding: rounding)

    }

    

    func rounded(secondsTimeIntervalroundingDateRoundingType = .round) -> Date {

        var roundedInterval: TimeInterval = 0

        switch rounding  {

        case .round:

            roundedInterval = (timeIntervalSinceReferenceDate / seconds).rounded() * seconds

        case .ceil:

            roundedInterval = ceil(timeIntervalSinceReferenceDate / seconds) * seconds

        case .floor:

            roundedInterval = floor(timeIntervalSinceReferenceDate / seconds) * seconds

        }

        return Date(timeIntervalSinceReferenceDate: roundedInterval)

    }

    

    func startDayOfDate() -> Date {

        return Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, ofself) ?? Date()

    }

    

    func endDayOfDate() -> Date {

        return Calendar.current.date(bySettingHour: 23, minute: 59, second: 59, ofself) ?? Date()

    }

}

 

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift