DateHelper - A high performant Swift Date Extension for creating, converting, comparing, or modifying dates.

Overview

DateHelper

License Platform Cocoapods Compatible Carthage Compatible Swift Package Manager Compatible

Sample Project Screenshot

A high performant Swift Date Extension for creating, converting, comparing, or modifying dates.

Capabilities

Creating a Date from a String

Provides two initializers to create a date from string.

  • detectFromString:
    init?(detectFromString string: String)
    Uses NSDataDetector to detect a date from natural language in a string. It works similar to how Apple Mail detects dates. This initializer is not as efficient as fromString:format: and should not be used in collections like lists.
Date(detectFromString: "It happened on August 11 of 2009")
Date(detectFromString: "Tomorrow at 5:30 PM")
  • fromString:format:
    init?(fromString string: String, format:DateFormatType, timeZone: TimeZoneType = .local, locale: Locale = Foundation.Locale.current, isLenient: Bool = true)
    Initializes a date from a string using a strict or custom format that is cached, highly performant and thread safe.
 Date(fromString: "2009", format: .isoYear)
 Date(fromString: "2009-08", format: .isoYearMonth)
 Date(fromString: "2009-08-11", format: .isoDate)
 Date(fromString: "2009-08-11T06:00-07:00", format: .isoDateTime)
 Date(fromString: "2009-08-11T06:00:00-07:00", format: .isoDateTimeSec)
 Date(fromString: "2009-08-11T06:00:00.000-07:00", format: .isoDateTimeMilliSec)
 Date(fromString: "/Date(1260123281843)/", format: .dotNet)
 Date(fromString: "Fri, 09 Sep 2011 15:26:08 +0200", format: .rss)
 Date(fromString: "09 Sep 2011 15:26:08 +0200", format: .altRSS)
 Date(fromString: "Wed, 01 03 2017 06:43:19 -0500", format: .httpHeader)
 Date(fromString: "16 July 1972 6:12:00", format: .custom("dd MMM yyyy HH:mm:ss"))

Convert a Date to a String

Provides three ways to convert a Date object to string

  • toString(style:)
    func toString(style:DateStyleType = .short) -> String
    Converts a date to string based on a pre-desfined style
Date().toString(style: .short)
Date().toString(style: .medium)
Date().toString(style: .long)
Date().toString(style: .full)
Date().toString(style: .ordinalDay)
Date().toString(style: .weekday)
Date().toString(style: .shortWeekday)
Date().toString(style: .veryShortWeekday)
Date().toString(style: .month)
Date().toString(style: .shortMonth)
Date().toString(style: .veryShortMonth)
  • toString(format:)
    func toString(format: DateFormatType, timeZone: TimeZoneType = .local, locale: Locale = Locale.current) -> String
    Converts a date to string based on a predefined or custom format
Date().toString(format: .custom("MMM d, yyyy"))
Date().toString(format: .custom("h:mm a"))
Date().toString(format: .custom("MMM d"))
Date().toString(format: .custom("MMM d"))
Date().toString(format: .isoYear)
Date().toString(format: .isoYearMonth)
Date().toString(format: .isoDate)
Date().toString(format: .isoDateTime)
Date().toString(format: .isoDateTimeSec)
Date().toString(format: .isoDateTimeMilliSec)
Date().toString(format: .dotNet)
Date().toString(format: .rss)
Date().toString(format: .altRSS)
Date().toString(format: .httpHeader)
  • toString(dateStyle:timeStyle)
    func toString(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style, isRelative: Bool = false, timeZone: Foundation.TimeZone = Foundation.NSTimeZone.local, locale: Locale = Locale.current) -> String
    Converts a date to string based on a predefined date and time style
Date().toString(dateStyle: .none, timeStyle: .short)
Date().toString(dateStyle: .short, timeStyle: .none)
Date().toString(dateStyle: .short, timeStyle: .short)
Date().toString(dateStyle: .medium, timeStyle: .medium)
Date().toString(dateStyle: .long, timeStyle: .long)
Date().toString(dateStyle: .full, timeStyle: .full)

Compare Dates

Provides common checks like isToday or isNextWeek. It can also check against another date like isSameDay or isEarlier.

  • Quick Checks
    Checks date against common scenarios
    func compare(_ comparison: DateComparisonType) -> Bool
Date().compare(.isToday) 
Date().compare(.isTomorrow)
Date().compare(.isYesterday)
Date().compare(.isThisWeek)
Date().compare(.isNextWeek)
Date().compare(.isLastWeek)
Date().compare(.isThisYear)
Date().compare(.isNextYear)
Date().compare(.isLastYear)
Date().compare(.isInTheFuture)
Date().compare(.isInThePast)
  • Comparing Dates
    Checks first date against second date
    func compare(_ comparison: DateComparisonType) -> Bool
firstDate.compare(.isSameDay(as: secondDate))
firstDate.compare(.isSameWeek(as: secondDate))
firstDate.compare(.isSameMonth(as: secondDate))
firstDate.compare(.isSameYear(as: secondDate))
firstDate.compare(.isEarlier(than: secondDate))
firstDate.compare(.isLater(than: secondDate))

Adjust dates

Provides two functions for adjusting dates

  • adjust(_ component:, offset:)
    Offsets the specified date compontent of a date
    func adjust(_ component:DateComponentType, offset:Int) -> Date
Date().adjust(.second, offset: 110)
Date().adjust(.minute, offset: 60)
Date().adjust(.hour, offset: 2)
Date().adjust(.day, offset: 1)
Date().adjust(.weekday, offset: 2)
Date().adjust(.nthWeekday, offset: 1)
Date().adjust(.week, offset: 1)
Date().adjust(.month, offset: 1)
Date().adjust(.year, offset: 1)
  • adjust(hour:minute:second:)
    Offsets the specified time component of the date
    func adjust(hour: Int?, minute: Int?, second: Int?, day: Int? = nil, month: Int? = nil) -> Date
Date().adjust(hour: 12, minute: 0, second: 0)

Create Dates for...

Provides convenience date creators for common scenarios like endOfDay, startOfDay etc.
func dateFor(_ type:DateForType, calendar:Calendar = Calendar.current) -> Date

Date().dateFor(.startOfDay)
Date().dateFor(.endOfDay)
Date().dateFor(.startOfWeek)
Date().dateFor(.endOfWeek)
Date().dateFor(.startOfMonth)
Date().dateFor(.endOfMonth)
Date().dateFor(.tomorrow)
Date().dateFor(.yesterday)
Date().dateFor(.nearestMinute(minute:30))
Date().dateFor(.nearestHour(hour:2)) 
Date().dateFor(.startOfYear)
Date().dateFor(.endOfYear)

Time since...

Returns a number in the specified unit of measure since the secondary date.
func since(_ date:Date, in component:DateComponentType) -> Int64

Date().since(secondDate, in: .second)
Date().since(secondDate, in: .minute)
Date().since(secondDate, in: .hour)
Date().since(secondDate, in: .day)
Date().since(secondDate, in: .week)
Date().since(secondDate, in: .nthWeekday)
Date().since(secondDate, in: .week)
Date().since(secondDate, in: .month)
Date().since(secondDate, in: .year)  

Miscellaneous

Setting the start day of the week

var calendar = Calendar(identifier: .gregorian)
calendar.firstWeekday = 2 // sets the week to start on Monday
Date().dateFor(.startOfWeek, calendar: calendar)

Extracting components from a date.

Date().component(.second)
Date().component(.minute)
Date().component(.hour)
Date().component(.day)
Date().component(.weekday)
Date().component(.nthWeekday)
Date().component(.month)
Date().component(.year)

Extracting miscellaneous items from a date.

Date().numberOfDaysInMonth()
Date().firstDayOfWeek()
Date().lastDayOfWeek()

Custom Component guide

Unicode Date Field Symbol Guide

Format Description Example
"y" 1 digit min year 1, 42, 2017
"yy" 2 digit year 01, 42, 17
"yyy" 3 digit min year 001, 042, 2017
"yyyy" 4 digit min year 0001, 0042, 2017
"M" 1 digit min month 7, 12
"MM" 2 digit month 07, 12
"MMM" 3 letter month abbr. Jul, Dec
"MMMM" Full month July, December
"MMMMM" 1 letter month abbr. J, D
"d" 1 digit min day 4, 25
"dd" 2 digit day 04, 25
"E", "EE", "EEE" 3 letter day name abbr. Wed, Thu
"EEEE" full day name Wednesday, Thursday
"EEEEE" 1 letter day name abbr. W, T
"EEEEEE" 2 letter day name abbr. We, Th
"a" Period of day AM, PM
"h" AM/PM 1 digit min hour 5, 7
"hh" AM/PM 2 digit hour 05, 07
"H" 24 hr 1 digit min hour 17, 7
"HH" 24 hr 2 digit hour 17, 07
"m" 1 digit min minute 1, 40
"mm" 2 digit minute 01, 40
"s" 1 digit min second 1, 40
"ss" 2 digit second 01, 40
"S" 10th's place of fractional second 123ms -> 1, 7ms -> 0
"SS" 10th's & 100th's place of fractional second 123ms -> 12, 7ms -> 00
"SSS" 10th's & 100th's & 1,000's place of fractional second 123ms -> 123, 7ms -> 007

Requirements

Language: Swift 5.0 Minimum: iOS 11, tvOS 12, watchOS 4, macOS 10.14

Installation

Swift Package Manager https://github.com/melvitax/DateHelper.git
Carthage github "melvitax/DateHelper"
Manually Include DateHelper.swift in your project
CocodaPods NO LONGER SUPPORTED

Author

Melvin Rivera

License

DateHelper is available under the MIT license. See the LICENSE file for more info.

Comments
  • Swift 3

    Swift 3

    First, I can't make a branch for you, so this PR should really have a base of some branch you'd create.

    It's interesting that this becomes a category on the new Date struct instead of the old NSDate class. That said it doesn't seem to have changed any behavior that I can see. Let me know if I can do anything to help.

    opened by ghost 9
  • Error on build: 'ISO8601DateFormatter' is only available in iOS 10.0 or newer

    Error on build: 'ISO8601DateFormatter' is only available in iOS 10.0 or newer

    I have a project that is iOS 14 and up. I'm getting a message 'ISO8601DateFormatter' is only available in iOS 10.0 or newer The package.swift of the DateHelper says v9 I'm wondering if it should be at least v10 if your using the ISO8601DateFormatter

    opened by Prince2k3 6
  • Not able to build with Xcode 12

    Not able to build with Xcode 12

    Screenshot 2020-11-02 at 12 32 48 PM

    Please let me know how can I fix this .

    I have tried few ways to get rid of like keychain Login lock and Unlock ,Updating the pods,Updating the cocoa pods but found no luck .

    opened by shireesh1993 6
  • Day Suffix

    Day Suffix

    Might be nice to add a day suffix to the library. Something like:

    `extension Date {

    static func getSuffix(forDate date: Date) -> String {
        if let day = date.component(.day) {
            let st: Set = [1, 21, 31]
            let nd: Set = [2, 22]
            let rd: Set = [3, 23]
            if st.contains(day) {
                return "st"
            }
            else if nd.contains(day) {
                return "nd"
            }
            else if rd.contains(day) {
                return "rd"
            }
            else {
                return "th"
            }
        } else {
            return ""
        }
    }
    

    }`

    Thanks!

    opened by Chazzman 6
  • Redundant Info.plist file

    Redundant Info.plist file

    When installing using pods workspace contains redundant Info.plist file in pod root folder. This blocks uploading build to AppStore (while simulator is still able to run app)

    opened by SanjoDeundiak 6
  • Date incorrect when raw

    Date incorrect when raw

    Hi, I have saved a date yesterday and it reads -- 2018-04-11 21:09:27 +0000

    Though today I printed todays date which should be 2018-04-12 21:09:27 +0000 reads → 2018-04-11 21:59:18 +0000

    This is fixed when I print it to a string but it is not correct when working with the raw" Date". I'm trying to compare the date I saved yesterday to today and it returns it is the same day.

    Thanks in advance for your help.

    opened by Ged2323 5
  • Caching of formatter doesn't work

    Caching of formatter doesn't work

            let locale = Locale(identifier: "en_US_POSIX")
    
            let str = "2017-07-19T14:32:20.000+03:00"
    
            let format = "yyyy-MM-dd\'T\'HH:mm:ss.SSSZ"
    
            let d1 = Date(fromString: str, format: .custom(format), locale: locale)
    
            let d2 = Date(fromString: str, format: .custom(format), locale: locale)
    
            print(d1)
            print(d2)
    

    Put the breakpoint at cachedFormatter, it always tries to create a new formatter and cached formatters is always empty

    opened by Vasant-Patel 5
  • Need to exclude Info.plist resource from Package.swift to resolve build warning

    Need to exclude Info.plist resource from Package.swift to resolve build warning

    When building with version 4.5.3, I get a warning:

    "found 1 file(s) which are unhandled; explicitly declare them as resources or exclude from the target /[Path snipped]/SourcePackages/checkouts/DateHelper/Sources/Info.plist"

    I think the Info.plist resource needs to be excluded from the Package.swift file to resolve the warning.

    Here's an example of aws-amplify resolved the same issue: https://github.com/aws-amplify/amplify-ios/pull/1163/commits/c659a2653caa6351eb578dd7b8defa92af701835

    opened by atticus 3
  • Feature Request: Allow checking the RelativeTimeStringType of a Date

    Feature Request: Allow checking the RelativeTimeStringType of a Date

    Currently toStringWithRelativeTime uses RelativeTimeStringType to output Strings. However, there is no way to determine which RelativeTimeStringType a Date falls into without looking at the output string of toStringWithRelativeTime.

    It would be nice to be able to get the RelativeTimeStringType of a Date directly with something like

    Date().toRelativeTime() // .nowPast
    

    or

    Date().is(.nowPast) // true
    

    This could allow for additional logic switching off of the RelativeTimeStringType of a Date, rather than just converting to a String.

    opened by emma-k-alexandra 3
  • Improved thread safety

    Improved thread safety

    Encountered data races and access violation crashes due to the cached date formatters array while using the library. I fixed it by wrapping it in a class and adding a dispatch queue/lock.

    I left the new class as an internal private subclass of the Date extension but it could be moved if desired. This may not fix all multi threading issues, but so far that is the only one I've encountered.

    opened by QuestofIranon 3
  • Error 'range(at:)' has been renamed to 'rangeAt(_:)'

    Error 'range(at:)' has been renamed to 'rangeAt(_:)'

    I get this error every time I update pods line 34 in DateHelper.swift .../Pods/AFDateHelper/Sources/DateHelper.swift:34:77: 'range(at:)' has been renamed to 'rangeAt(_:)'

    let dateString = (string as NSString).substring(with: match.range(at: 1)) Update to let dateString = (string as NSString).substring(with: match.rangeAt(1)) then it is ok...

    opened by emonster 3
  • Compare with `date.compare(.isEarlier(than: ))` return true if two day's  timeIntervalSince1970 are equal

    Compare with `date.compare(.isEarlier(than: ))` return true if two day's timeIntervalSince1970 are equal

    https://github.com/melvitax/DateHelper/blob/master/Sources/DateHelper/DateHelper.swift#L261-L264

    let date = Date.now
    print(date.compare(.isEarlier(than: date))) // true
    
    opened by alfredcc 3
  • style: month/shortMonth/veryShotMonth return wrong result

    style: month/shortMonth/veryShotMonth return wrong result

    code:

            var date = Date(fromString: "2009-08-11T06:00:00.000-07:00", format: .isoDateTimeFull)
            print(date)
            print("----------------------------------------------")
            print(date?.toString(format: .isoYearMonth))
            print("----------------------------------------------")
            print(date?.toString(style: .month))
            print(date?.toString(style: .shortMonth))
            print(date?.toString(style: .veryShortMonth))
    

    output:

    Optional(2009-08-11 13:00:00 +0000)
    ----------------------------------------------
    Optional("2009-08")
    ----------------------------------------------
    Optional("March")
    Optional("Mar")
    Optional("M")
    
    opened by dean-nxa 0
  • Restore Carthage support

    Restore Carthage support

    I would like to allow Carthage support again.

    In the commit “Updated to a proper package manager directory structure (63b9f98)” the schemes that allow support using Carthage were removed.

    I guess it's because now priority is given to SPM, but for now it's compatible with supporting Carthage. That's why I propose to restore support.

    opened by jose-gil 0
  • .fromString always return nil

    .fromString always return nil

    Hi,

    I am trying to create Date object from time string, but without success:

    print(Date(fromString: "16:12:00", format: .custom("HH:mm:ss"))?.toString(format: .custom("MMM d, yyyy HH:mm")))
    

    The result is nil. Can I get some help?

    opened by MrEldin 0
  • This should

    This should "just" return

    This line falls through to return nil when it should just return empty

    https://github.com/melvitax/DateHelper/blob/76d0840daab7288fc99b04a4c23d504f0394e083/Sources/DateHelper/DateHelper.swift#L52

    opened by pec1985 0
Releases(5.0.1)
Owner
Melvin Rivera
UX Designer and Programmer
Melvin Rivera
Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse

Date Formatter Pool Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse Installation is available i

Aleksei Artemev 13 Sep 6, 2022
SwiftDate 🐔 Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift.

Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift. What's This? SwiftDate is the definitive toolchain to ma

Daniele Margutti 7.2k Jan 4, 2023
Punctual - Swift dates, more fun. Heavily inspired by ObjectiveSugar

Punctual Swift dates, more fun. Heavily inspired by ObjectiveSugar Installation Punctual is available through the Swift Package Manager! Just add this

Harlan Haskins 321 Jun 30, 2022
Dates and times made easy in iOS

DateTools DateTools was written to streamline date and time handling in iOS. Classes and concepts from other languages served as an inspiration for Da

Matthew York 7.2k Dec 30, 2022
A Cocoa NSFormatter subclass to convert dates to and from ISO-8601-formatted strings. Supports calendar, week, and ordinal formats.

ISO 8601: The only date format worth using Obligatory relevant xkcd: How to use this code in your program Add the source files to your project. Parsin

Peter Hosey 601 Sep 4, 2022
🕐 Format your dates/times as emojis.

EmojiTimeFormatter Format your dates/times as emojis ?? ?? ?? Description You can build easy to understand user interfaces with EmojiTimeFormatter or

Thomas Paul Mann 80 Feb 7, 2022
NVDate is an extension of NSDate class (Swift4), created to make date and time manipulation easier.

NVDate is an extension of NSDate class (Swift4), created to make date and time manipulation easier. NVDate is testable and robust, we wrote intensive test to make sure everything is safe.

Noval Agung Prayogo 177 Oct 5, 2022
📆 Breeze through Date, DateComponents, and TimeInterval with Swift!

Datez ?? Breeze through Date, DateComponents, and TimeInterval Highlights Two Custom Structs Only (value types FTW!): DateView: An Date associated wit

Kitz 263 Dec 7, 2022
Intuitive date handling in Swift

Timepiece Intuitive date handling in Swift Features ?? Intuitive: Timepiece provides a set of helpers to make date handling easier. ?? Correct: Using

Naoto Kaneko 2.6k Dec 22, 2022
Elegant NTP date library in Swift

Kronos is an NTP client library written in Swift. It supports sub-seconds precision and provides a stable monotonic clock that won't be affected by ch

Mobile Native Foundation 575 Dec 23, 2022
Building a better date/time library for Swift

Time Time is a Swift package that makes dealing with calendar values a natural and straight-forward process. Working with calendars can be extremely c

Dave DeLong 2k Dec 31, 2022
Swift Date Formatter

Swift Date Formatter Date Formatter - Sample code on how to use Date Formatter in swift language Author: Denow Cleetus For OSSE Assignment 4 Group 24

Denow Cleetus 0 Nov 7, 2021
NasaApod - iOS, Swift, MVVM, Consuming NASA Astronomy Picture of the Day API for any selected date

NasaApod iOS, Swift, MVVM, Unit Tests Consuming NASA Astronomy Picture of the Da

Vishal Singh 1 Jan 10, 2022
🎗 Super lightweight ISO8601 Date Formatter in Swift

ISO8601 ❤️ Support my apps ❤️ Push Hero - pure Swift native macOS application to test push notifications PastePal - Pasteboard, note and shortcut mana

Khoa 19 May 12, 2020
Date and time manager for iOS/OSX written in Swift

Tempo was designed to work both in OSX and in iOS (7.0+). Work with the time or dates can be cumbersome, iOS development. Tempo allows you to deal easly with date and time. Basics manipulations are already implemented in Tempo.

Remi ROBERT 153 Jun 3, 2021
Swifty Date & Time API inspired from Java 8 DateTime API.

AnyDate Swifty Date & Time API inspired from Java 8 DateTime API. Background I think that date & time API should be easy and accurate. Previous dates,

Jungwon An 182 Dec 1, 2022
Datify 🕛 Easypeasy date functions.

Datify ?? Easypeasy date functions.

Hemang 44 Dec 6, 2022
A customizable date picker for watchOS and SwiftUI.

Watch Date Picker A customizable date picker for watchOS and SwiftUI. Installation .package(url: "https://github.com/freyaariel/watch-date-picker.git"

Freya Ariel 30 Dec 4, 2022
A basic countdown app that allows the user to create, edit, and delete events. Each event contains a live countdown timer to a specified date and time.

Event Countdown App (iOS) Created by Lucas Ausberger About This Project Created: January 4, 2021 Last Updated: January 8, 2021 Current Verison: 1.1.1

Lucas Ausberger 1 Jan 8, 2022