Skip to content

Instantly share code, notes, and snippets.

@mohsinbmwm3
Last active January 18, 2021 14:28
Show Gist options
  • Save mohsinbmwm3/5879d0db826b67f7c57079be608ac50e to your computer and use it in GitHub Desktop.
Save mohsinbmwm3/5879d0db826b67f7c57079be608ac50e to your computer and use it in GitHub Desktop.
Some useful date extension ideas I have in my mind. Please take a look.
import Foundation
extension DateFormatter {
static let instance = DateFormatter()
// You can also add multiple date formatters, creating date formater is very heavy task,
// It is not advisable to create instance of it every time you want to use it.
}
extension Calendar {
// Shorthands for different calendar
static let gregorianCalendar = Calendar(identifier: .gregorian)
static let indianCalendar = Calendar(identifier: .indian)
static let chineseCalendar = Calendar(identifier: .chinese)
}
extension TimeZone {
// Shorthands for different timezones
static let utcTimeZone = TimeZone(identifier: "UTC")
static let indianTimeZone = TimeZone(identifier: "IST")
}
extension Date {
func toString(format: String = "EEE, dd MM yyyy") -> String {
// Crating date formatter instance is very heavy operation, i would recomend to create dateformatter instance only once and use it globally
DateFormatter.instance.dateStyle = .short
DateFormatter.instance.dateFormat = format
return DateFormatter.instance.string(from: self)
}
func timeIn24HourFormat() -> String {
DateFormatter.instance.dateStyle = .none
DateFormatter.instance.dateFormat = "HH:mm"
return DateFormatter.instance.string(from: self)
}
func firstDateOfMonth() -> Date {
var components = Calendar.current.dateComponents([.year, .month], from: self)
components.day = 1
let firstDateOfMonth = Calendar.current.date(from: components)!
return firstDateOfMonth
}
func lastDateOfMonth() -> Date {
return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: self.firstDateOfMonth())!
}
func nextDate() -> Date {
let nextDate = Calendar.current.date(byAdding: .day, value: 1, to: self)
return nextDate ?? Date()
}
func previousDate() -> Date {
let previousDate = Calendar.current.date(byAdding: .day, value: -1, to: self)
return previousDate ?? Date()
}
func addMonths(numberOfMonths: Int) -> Date {
let result = Calendar.current.date(byAdding: .month, value: numberOfMonths, to: self)
return result ?? Date()
}
func substractMonths(numberOfMonths: Int) -> Date {
let result = Calendar.current.date(byAdding: .month, value: -numberOfMonths, to: self)
return result ?? Date()
}
func addYears(numberOfYears: Int) -> Date {
let result = Calendar.current.date(byAdding: .year, value: numberOfYears, to: self)
return result ?? Date()
}
func substractYears(numberOfYears: Int) -> Date {
let result = Calendar.current.date(byAdding: .year, value: -numberOfYears, to: self)
return result ?? Date()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment