Created
November 23, 2021 10:35
-
-
Save waseem-pk/ea858298b83102511ec3eb64e2a606fb to your computer and use it in GitHub Desktop.
Date Extension for Swift iOS
This file contains 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
//MARK:- DATE | |
extension Date { | |
func toSString_ServerFormat() -> String { | |
let dateFormatter = DateFormatter() | |
dateFormatter.timeZone = .current | |
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" | |
let str = dateFormatter.string(from: self) | |
return str | |
} | |
/// Returns the amount of days from another date | |
func days() -> Int { | |
return Calendar.current.dateComponents([.day], from: self, to: Date() ).day ?? 0 | |
} | |
func adding(seconds: Int) -> Date { | |
return Calendar.current.date(byAdding: .second, value: seconds, to: self)! | |
} | |
func adding(minutes: Int) -> Date { | |
return Calendar.current.date(byAdding: .minute, value: minutes, to: self)! | |
} | |
func adding(hours: Int) -> Date { | |
return Calendar.current.date(byAdding: .hour, value: hours, to: self)! | |
} | |
func adding(days: Int) -> Date { | |
return Calendar.current.date(byAdding: .day, value: days, to: self)! | |
} | |
func adding(months: Int) -> Date { | |
return Calendar.current.date(byAdding: .month, value: months, to: self)! | |
} | |
func adding(years: Int) -> Date { | |
return Calendar.current.date(byAdding: .year, value: years, to: self)! | |
} | |
func minusSeconds(from date: Date) -> Int { | |
return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0 | |
} | |
struct Formatter { | |
static let iso8601: DateFormatter = { | |
let formatter = DateFormatter() | |
formatter.calendar = Calendar(identifier: .iso8601) | |
formatter.locale = Locale(identifier: "en_PK") // en_US_POSIX | |
formatter.timeZone = TimeZone(secondsFromGMT: 0) | |
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" | |
return formatter | |
}() | |
} | |
var iso8601: String { | |
return Formatter.iso8601.string(from: self) | |
} | |
static func -(recent: Date, previous: Date) -> (month: Int?, day: Int?, hour: Int?, minute: Int?, second: Int?) { | |
let day = Calendar.current.dateComponents([.day], from: previous, to: recent).day | |
let month = Calendar.current.dateComponents([.month], from: previous, to: recent).month | |
let hour = Calendar.current.dateComponents([.hour], from: previous, to: recent).hour | |
let minute = Calendar.current.dateComponents([.minute], from: previous, to: recent).minute | |
let second = Calendar.current.dateComponents([.second], from: previous, to: recent).second | |
return (month: month, day: day, hour: hour, minute: minute, second: second) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment