Swifty Date & Time API inspired from Java 8 DateTime API.

Overview

AnyDate

Awesome Swift Carthage compatible Version License CI Status Codecov Platform Jazzy

Swifty Date & Time API inspired from Java 8 DateTime API.

Background

I think that date & time API should be easy and accurate.

Previous dates, times, timezones API of Swift are inconvenience to use. (It's very complex to create, manipulate or everything else.)

But there's quite nice pioneer, The Brand New Time API of Java8.

Java 8 introduced whole new API for handle date & time more efficiently and easy a.k.a LocalDateTime, ZonedDateTime(JSR-310). The main idea that is:

  • Immutable-value classes
  • Domain-driven design
  • Separation of chronologies

Those ideas can be easily ported to another languages, like .Net's Rx ports of another languages.

So, here's the AnyDate, whole new Swift date & time API that has coherence between Java 8.

Features

  • Convinience typed year, month, day, time.
  • Pre-defined Timezone Identifiers.
  • Null-Safe types.
  • Separation of chronologies.
  • Coherence with Java.
  • Operators supported.
  • Easy to manipulate.

FAQ

  • Looks like SwiftDate?
    • SwiftDate is a support library for Date, AnyDate can completely replace Date.

Usage

  • Convinience typed year, month, day, time.
/// Before
let now1 = Date()
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "UTC")!

let day = calendar.components(.day, from: now1)

/// After
let now2 = ZonedDateTime(Clock.utc)
let day = now2.day
  • Pre-defined Timezone Identifiers. String typed timezones are not safe from your TYPING ERROR. (Plz, do not belive your finger. They can always betray you.)
/// Before
let timeZone1 = TimeZone(identifier: "GMT+0900")!
let timeZone2 = TimeZone(identifier: "America/Argentina/Buenos_Aires")!

/// After
let clock1 = Clock(offsetHour: 9)
let clock2 = Clock(identifier: .americaArgentinaBuenosAires)
  • Null-Safe types. NO MORE NEEDLESS GUARD & OPTIONAL AND INDENT INCRESEMENT :-D
/// Before
var dateComponents = DateComponents()
dateComponents.year = 2000
dateComponents.month = 11
dateComponents.day = 30
dateComponents.hour = 11
dateComponents.minute = 51
dateComponents.second = 18
dateComponents.nanosecond = 1573

guard let date = Calendar.current.date(from: dateComponents) else {
    assertionFailure("Failed to create!")
    return
}

/// After
let date = LocalDateTime(
    year: 2000,
    month: 11,
    day: 30,
    hour: 11,
    minute: 51,
    second: 18,
    nanoOfSecond: 1573
)
  • Operators supported. Easy to compare dates, datetimes, times.
let min = ZonedDateTime.min
let max = ZonedDateTime.max

let oldDate = ZonedDateTime(year: 1627, month: 2, day: 10, hour: 14, minute: 2, second: 18, nanoOfSecond: 1573, clock: .UTC)
let newDate = ZonedDateTime(year: 1627, month: 2, day: 10, hour: 14, minute: 2, second: 18, nanoOfSecond: 1574, clock: .UTC)
let equalDate = ZonedDateTime(year: 1627, month: 2, day: 10, hour: 14, minute: 2, second: 18, nanoOfSecond: 1573, clock: .UTC)

let isLessThan = min < oldDate
let isGreaterThan = max > newDate
let isLessThanOrEqual = oldDate <= equalDate
let isGreaterThanOrEqual = oldDate >= equalDate
let isEqual = oldDate == equalDate
let isLessThan = oldDate < newDate
  • Easy to manipulate. You can use our overridden operators to create / add / sub dates and times.
/// 1000-01-07T11:51:18.000001573
let date = LocalDateTime(
    year: 1000,
    month: 1,
    day: 7,
    hour: 11,
    minute: 51,
    second: 18,
    nanoOfSecond: 1573
)
print(date)

/// Period(year: 1, month: 1, day: 9, hour: 2, minute: 3, second: 4, nano: 152)
let period = 1.year + 1.month + 1.week + 2.day + 2.hour + 3.minute + 4.second + 152.nanosecond

/// 1001-03-16T13:54:22.000001725
let newDate = date + period
print(newDate)

Installation

CocoaPods:

pod 'AnyDate', '~> 1.2.0'

Carthage:

github "kawoou/AnyDate" ~> 1.2.0

Swift Package Manager:

import PackageDescription

let package = Package(
  name: "MyAwesomeApp",
  dependencies: [
    .Package(url: "https://github.com/kawoou/AnyDate", majorVersion: 1),
  ]
)

Manually

You can either simply drag and drop the Sources folder into your existing project.

Requirements

  • Swift 3.1
  • iOS 8.0+
  • tvOS 9.0+
  • macOS 10.10+
  • watchOS 2.0+
  • Virtually any platform which is compatible with Swift 3 and implements the Swift Foundation Library.

Changelog

  • 1.0.0 - 2017/08/13
    • First release AnyDate!
  • 1.0.1 - 2017/08/16
    • Increase test codes.
    • Implement CustomPlaygroundQuickLookable, CustomReflectable protocols.
  • 1.0.2 - 2017/08/26
    • Increase test codes.
    • Support Codable protocol in swift 4.
    • Add operators on Instant.
  • 1.0.3 - 2017/09/03
    • Hotfix, Comparable bugs.
  • 1.0.4 - 2017/10/07
    • Fix Calendar(identifier: .iso8601) crash on swift SR-3828.
  • 1.0.5 - 2018/04/11
    • Support for Swift 4.1 and Xcode 9.3.
  • 1.0.6 - 2018/05/20
    • Support Hashable.
  • 1.1.0 - 2018/10/18
    • Support for Swift 4.2.
  • 1.2.0 - 2019/04/04
    • Support for Swift 5.0.

Author

Special Thanks

  • Naming by 아메바

License

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

Comments
  • LocalDate/Time Comparables logic error

    LocalDate/Time Comparables logic error

    I found an error within LocalTime, probably concern LocalDate/LocalDateTime as well. Given two times: 17:50:23:372247993 > 17:57:39:0 will return true Left is clearly before, however, since left nano is greater than right nano, left will be wrongly considered superior.

    bug 
    opened by ddcrobert 2
  • Notify long term release plan and roadmap

    Notify long term release plan and roadmap

    I think, this project's maintainer @Kawoou has to notify to everyone, the Long Term Release Plan.

    I guess that you have quite much more ideas about Swift's useful Date & Time Library, so please tell us your roadmap.

    opened by DaveDev42 2
  • Make value types conform to Hashable

    Make value types conform to Hashable

    Value types like LocalDate should conform to the Hashable protocol so they can be used as dictionary keys.

    We could just take the implementation directly from the hashCode() methods in java.time. For example, java.time.LocalDate has the following implementation of hashCode():

    public int hashCode() {
      int yearValue = this.year;
      int monthValue = this.month;
      int dayValue = this.day;
      return yearValue & -2048 ^ (yearValue << 11) + (monthValue << 6) + dayValue;
    }
    
    opened by mattlogan 1
  • Error: Segmentation fault (core dumped) on Linux

    Error: Segmentation fault (core dumped) on Linux

    SO: Ubuntu 16.04 Swift: 3.1

    Code:

    print("starting \(market.marketStartTime!)")
    let gmt = Clock.GMT
    print("2")
     var marketStartTime = ZonedDateTime.parse(market.marketStartTime!, clock: gmt)
    print("3")
     marketStartTime = marketStartTime?.plus(minute: 3)
    print("4")
    

    Result:

    starting 2017-09-24T17:00:00.000Z
    2
    Segmentation fault (core dumped)
    
    bug 
    opened by klevison 1
  • Split Period into Period and Duration to maintain parity with java.time

    Split Period into Period and Duration to maintain parity with java.time

    It looks like you combined everything from java.time.Period and java.time.Duration into a single implementation of Period. While I don't disagree with this as a design decision, I think it's more important for the goals of this library (i.e. Java parity) to keep these as two separate classes.

    opened by mattlogan 0
  • Add lunar calendar system

    Add lunar calendar system

    What is lunar calendar?

    Lunar calendar

    Lunar calendar is a calendar based upon cycles of the Moon's phases.

    Gregorian calendar is also common and legal use in most countries, but also traditional lunar and lunisolar calendears continue to be used in many countries to determine religious festivals and national holidays.

    But, unfortunately, unlike gregorian calendar, there are several seperated lunar calendar systems:

    • Korean calendar
    • Chinese calendar
    • Japanese calendar
    • Vietnamese calendar
    • Mongolian calendar
    • Islamic calendar
    • Hebrew calendar

    I can strongly urge that: good application/solution/service have to understand about users and also their habit, tradition and life; even if they are using some unfamiliar calendar.

    If AnyDate supports about all other calendars, it can very helpful to development global things.

    opened by DaveDev42 1
  • Add features like ThreeTen-Extra

    Add features like ThreeTen-Extra

    What is ThreeTen-Extra

    ThreeTen-Extra

    ThreeTen-Extra provides additional date-time classes that complement those in Java SE 8.

    Features:

    • DayOfMonth
    • DayOfYear
    • AmPm
    • Quarter
    • YearQuarter
    • YearWeek
    • Days, Weeks, Months and Years
    • Interval
    • PeriodDuration
    • Weekend adjusters
    • Coptic calendar system
    • Ethiopic calendar system
    • Julian calendar system
    • Support for the TAI and UTC time-scales

    I know that few of these features already implemented in AnyDate, and yet other features seems be quite useful in Swift Application Programming.

    opened by DaveDev42 0
Releases(v1.2.0)
Owner
Jungwon An
Jungwon An
A "time ago", "time since", "relative date", or "fuzzy date" category for NSDate and iOS, Objective-C, Cocoa Touch, iPhone, iPad

Migration 2014.04.12 NSDate+TimeAgo has merged with DateTools. DateTools is the parent project and Matthew York is the project head. This project is n

Kevin Lawler 1.8k Dec 2, 2022
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
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
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
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
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 API for NSTimer

SwiftyTimer Modern Swifty API for NSTimer SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It

Radek Pietruszewski 1.2k Dec 29, 2022
This Control is a beautiful time-of-day picker heavily inspired by the iOS 10 "Bedtime" timer.

#10Clock Dark and Mysterious ?? Light Colors ?? Usage The control itsself is TenClock. Add that to your view hierarchy, and constrain it to be square

Joe 557 Dec 23, 2022
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
DateHelper - A high performant Swift Date Extension for creating, converting, comparing, or modifying dates.

DateHelper A high performant Swift Date Extension for creating, converting, comparing, or modifying dates. Capabilities Creating a Date from a String

Melvin Rivera 1.4k Jan 2, 2023
📆 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
Datify 🕛 Easypeasy date functions.

Datify ?? Easypeasy date functions.

Hemang 44 Dec 6, 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
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
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
🎗 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
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
Time is a Swift package that makes dealing with calendar values a natural and straight-forward process.

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