SwiftMoment - A time and calendar manipulation library for iOS 9+, macOS 10.11+, tvOS 9+, watchOS 2+ written in Swift 4.

Overview

SwiftMoment

Join the chat at https://gitter.im/SwiftMoment/Lobby Build Status CocoaPods Compatible Carthage Compatible Platform swiftyness

This framework is inspired by Moment.js. Its objectives are the following:

  • Simplify the manipulation and readability of date and interval values.
  • Provide help when parsing dates from various string representations.
  • Simplifying the formatting of date information into strings.
  • Streamlining getting date components (day, month, etc.) from dates and time intervals.

Important: This framework supports iOS 9+, macOS 10.11+, tvOS 9+, watchOS 2+, Xcode 8 and Swift 3.

Installation

SwiftMoment is compatible with Carthage and CocoaPods. With CocoaPods, just add this to your Podfile:

pod 'SwiftMoment'

SwiftMoment can also be used via the Swift Package Manager. Just add it to the dependencies in your Package.swift file:

let package = Package(
    name: "MyPackage",
    dependencies: [
        ...
        .package(url: "https://github.com/akosma/SwiftMoment.git", from: "0.7.1"),
    ],
    ...
)

Mac OS X Notes

  • Drag the created .framework file into the Xcode Project, be sure to tick 'Copy Files to Directory'
  • In the containing applications target, add a new 'Copy File Build Phase'
  • Set the 'Destination' to 'Frameworks'
  • Drag in the created .framework

Examples

To use this library, just import SwiftMoment in your application.

To create new moment instances:

let now = moment()
let yesterday = moment("2015-01-19")

By default, moments are initialized with the current date and time. You can create moments for any... moment in the future or the past; you can do that by passing strings in different formats:

let yesterday = moment("2015-01-19")

You can also do it by directly specifying the components manually:

let today = moment([2015, 01, 19, 20, 45, 34])

You can also use a dictionary with the following keys:

let obj = moment(["year": 2015,
                    "second": 34,
                    "month": 01,
                    "minute": 45,
                    "hour": 20,
                    "day": 19
                ])

When using a [String: Int] dictionary, the order of the keys does not matter. Moreover, only the keys above are taken into account, and any other information is ignored.

There is also an extension to the Int type in Swift, used to create Duration values directly from an integer value:

let duration = 5.hours + 56.minutes

Architecture

The two most important components of this library are the Moment and Duration structures. Moment wraps an NSDate instance, while Duration wraps an NSTimeInterval value.

Both Moment and Duration comply with the Comparable protocols, and include all the required operators. In addition, Moment instances can be subtracted from one another (which yields a Duration) and Duration instances can be added to Moments to create new moments.

Moments and Durations are made as immutable as possible.

Tests

Swift Moment includes a suite of tests showing how to use the different functions of the framework.

To run the Linux tests in a macOS environment, please use the included Dockerfile:

docker build --tag swiftmoment .
docker run --rm swiftmoment

Playground

A playground is included in the project to learn how to use the library.

Differences with Moment.js

  • Format strings DD and dd do not yield the same results.

Contributors

Lots of people are actively helping in the development of this library; please check the CONTRIBUTORS file for the full list! Thanks to all :)

License

This project is distributed under a BSD license. See the LICENSE file for details.

Comments
  • Update to Swift 2.0

    Update to Swift 2.0

    I did not do much apart from running it through the Xcode converter. The main changes are instead of using the full names for calendar components (eg CalendarUnitYear) we now use the enum (eg .Year).

    opened by armstrongnate 8
  • fromNow() returning

    fromNow() returning ""

    This part is messing around

        private func NSDateTimeAgoLocalizedStrings(key: String) -> String {
          // get framework bundle
          let bundleIdentifier = "com.akosma.SwiftMoment"
          guard let frameworkBundle = NSBundle(identifier: bundleIdentifier) else {
            return "" <<----
          }
    

    PS: I'm using pods

    opened by akabab 7
  • Unit tests are time zone specific

    Unit tests are time zone specific

    testCanCreateWeirdDateFromComponents() and testFormatDates() fail if run in Chicago, IL because the expected result is time zone-specfic. This is because NSDateFormatter uses the local time zone.

    opened by getaaron 7
  • Function Moment.add(value: Int, _ unit: TimeUnit) -> Moment goes wrong.

    Function Moment.add(value: Int, _ unit: TimeUnit) -> Moment goes wrong.

    Line 413 in Moment.swift will cause unexpected result.

    cal.timeZone = NSTimeZone(abbreviation: "UTC")!
    

    For example:

    I have a date: "2016-07-01 00:00:00 GMT+08:00", then I called date.add(1, .Months), I expect to get "2016-08-01 00:00:00 GMT+08:00", but I only got "2016-07-30 16:00:00 GMT+00:00", which is "2016-07-31 00:00:00 GMT+08:00". You just convert my original date to "2016-06-30 16:00:00 GMT+00:00", then add a month. Bang!

    I modified this line as below:

    cal.timeZone = timeZone
    cal.locale = locale
    

    Then it went right, but I don't know is there any other errors it would cause.

    opened by asfara 5
  • Support OS X

    Support OS X

    Added an OS X Target and Test Target

    Supports OS X 10.10 and links to the original tests Tests Pass!

    To use in your OS X Project: http://stackoverflow.com/questions/24993752/os-x-framework-library-not-loaded-image-not-found

    Including The Framework Drag the created .framework file into the Xcode Project, be sure to tick 'Copy Files to Directory' In the containing applications target, add a new 'Copy File Build Phase' Set the 'Destination' to 'Frameworks' Drag in the created .framework

    opened by madhavajay 5
  • can't compile in Xcode 8.1

    can't compile in Xcode 8.1

    I use carthage. The version 0.7 can't be built but 0.6 works.

    Here is the failure output

    MomentTests.swift:13:1: error: Type Body Length Violation: Type body should span 350 lines or less excluding comments and whitespace: currently spans 400 lines (type_body_length)

    opened by qgliu 4
  • Time Zone not changing

    Time Zone not changing

    I'm trying to create a moment with GMT-0300 date, from a GMT date string with format "yyy-MM-dd'T'HH:mm:ss" by doing let timeZone = TimeZone(secondsFromGMT: -10800) let locale = Locale(identifier: "en_US_POSIX") let teste = moment(dateString, dateFormat: "yyy-MM-dd'T'HH:mm:ss", timeZone: timeZone!, locale: locale)

    For example: dateString = "2016-10-12T10:02:50" And I want my moment to store hour = 7, minute = 02

    No matter which TimeZone I use to create it, it always returns the time that was given in dateString. I couldn't find any documentation on this. Is there any way to to do so?

    opened by tatimagdalena 4
  • Inefficient use of NSDateFormatter

    Inefficient use of NSDateFormatter

    Instantiate NSDateFormatter is expensive operation and you use it exactly that way. You can read this in Apple documentation:

    Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable.

    bug 
    opened by tomassliz 4
  • Swift 2.3 compatibility

    Swift 2.3 compatibility

    It is needed to support swift 2.3 and I found out that just replacing codes in MomentFromNow.swift#104 to

    #if swift(>=2.3)
      let path = NSURL(fileURLWithPath:resourcePath).URLByAppendingPathComponent(bundleName)!
    #else
      let path = NSURL(fileURLWithPath:resourcePath).URLByAppendingPathComponent(bundleName)
    #endif
    

    makes XCode 8 build fine.

    So i'm ready for pulling request.

    Which is better?

    1. Support both version (swift2.2 and swift2.3) in master branch using #ifswift like above.
    2. Make another branch swift2.3 and split build environment into Xcode 7 and Xcode 8
    opened by momamene 3
  • Add Carthage support

    Add Carthage support

    Marked Xcode scheme as shared to support Carthage. I think a new tag will need to be created too - see here.

    Fixes this error when trying to use SwiftMoment with Carthage: Project "SwiftMoment.xcodeproj" has no shared schemes

    opened by chrissloey 3
  • Updated to Swift 4

    Updated to Swift 4

    • Fixed two tests and changed Moment isEqual comparator
    • Added fastlane to simplify testing
    • Changed .travis.yml to use fastlane
    • Fastlane does not support instrumenting macOS tests so we just build
    opened by madhavajay 2
  • Wrong date parsing

    Wrong date parsing

    Detailed Description

    When I try to parse the date in specific format I get one year backdate.

    Possible Implementation

    let day = moment("178-06-2019", dateFormat: "DD-MM-YYYY") returns // 2018-12-23 00:00:00 GMT+05:30

    Your Environment

    • Version used: (0.7)
    • Operating System and version: Xcode Playground
    opened by designway 0
  • Trouble Shooting in Swift 4

    Trouble Shooting in Swift 4

    I'm having problems running the framework in Swift 4 the project simply stops running when it comes to checking the framework SwiftMoment I'm in the latest version of Swift 4 and Xcode. If I'm not mistaken in this last update, the class set that started with NS was untouched. Xcode basically complains about all Swift class that starts with NS it complains.

    opened by joaoduartemariucio 1
  • Get Tomorrow's date

    Get Tomorrow's date

    I'm trying to get tomorrow's date like this, but it just returns today's.

    moment().add(1, "days").format("MMMM do")

    This works fine in Javascript moment().add(1, "days").format("MMMM Do")

    Your Environment

    Swift 4.0 Xcode Version 9.2 (9C40b)

    opened by keithmichelson 1
  • Subtracting months edge case - subtracts 30 days

    Subtracting months edge case - subtracts 30 days

    It seems to subtract 30 days instead of 1 whole month.

    Detailed Description

    If the starting date is 1/30/2018, and I subtract 1 month, it becomes 12/31/2017, I would have expected 12/30/2017. If I subtract 2 months, it becomes 12/01/2017. I would have expected it to be 11/30/2017.

    Your Environment

    • Version used: 0.7
    • Operating System and version: latest version of Swift, Xcode
    opened by phaddius 2
  • Device using Traditional Chinese in Taiwan (zh-Hant-TW) returning empty string

    Device using Traditional Chinese in Taiwan (zh-Hant-TW) returning empty string

    Detailed Description

    getLanguageBundle is returning nil. Strangely, locale.identifier is returning zh-TW, without the "Hant".

    The 2nd part of getLanguageBundle therefore only get the language code as zh.

    Since now the bundle only has zh-Hant, no localized string is found.

    Context

    Localization does not work for Taiwan app users.

    Possible Implementation

    I believe another fallback using Bundle to load will work.

    Your Environment

    • Version used: 0.7
    • Operating System and version: 11.2
    • Link to your project: -
    opened by samwize 1
Owner
Adrian Kosmaczewski
Developer Relations at VSHN. Co-creator of De Programmatica Ipsum. Professional closing keynote speaker. Public-Interest Technologist. Immigrant.
Adrian Kosmaczewski
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
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
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
Customizable Calendar SwiftUI Library

SwiftUI Customizable Calendar Library

LeeProgrammer 8 Oct 11, 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
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
NTP library for Swift and Objective-C. Get the true time impervious to device clock changes.

TrueTime for Swift Make sure to check out our counterpart too: TrueTime, an NTP library for Android. NTP client for Swift. Calculate the time "now" im

Instacart 530 Jan 4, 2023
SwiftUI library to display a clock. You can move the arms to change the time, change the style of the clock and customise some configurations.

SwiftClockUI Clock UI for SwiftUI This library has been tested ✅ ?? macOS Catalina 10.15.3 ✅ ?? macOS Big Sur 11.6 ✅ ?? iOS 13 ✅ ?? iOS 14 ✅ ?? iOS 15

Renaud Jenny 239 Dec 29, 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
Create your own faces for watchOS. Customize the watch hands, layout, colors, and images. Edit faces on your phone and switch them on the watch.

AppleWatchFaces Design your own watch faces for the apple watch. They are not real watch faces, but a watchOS app running on the watch that tells you

Mike Hill 395 Oct 20, 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 TimeZonePicker UIViewController similar to the iOS Settings app. Search and select from a range of cities and countries to find your most suitable time zone.

TimeZonePicker A TimeZonePicker UIViewController similar to the iOS Settings app. Search and select from a range of cities and countries to find your

Gligor Kotushevski 125 Dec 13, 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
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
Custom Time Picker ViewController with Selection of start and end times in Swift 🔶

LFTimePicker Custom Time Picker ViewController with Selection of start and end times in Swift ?? . Based on Adey Salyard's design @ Dribbble One to tw

Awesome Labs 65 Nov 11, 2022
Time Lines - Know when all your friends, colleagues, and family are

Time Lines Know when all your friends, colleagues, and family are. Time Lines is a practical app to know when all your friends, colleagues and family

Mathieu Dutour 50 Dec 14, 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
Better time picker for iOS.

TimePicker Better TimePicker for iOS Requirements Swift 5.0 iOS 10.0+ Xcode 10.2+ Installation The easiest way is through CocoaPods. Simply add the de

Oleh 14 Oct 21, 2022
The goal is a simple iOS app that draws an analog clock of the current time

Qrono This is a work-in-progress. The goal is a simple iOS app that draws an analog clock of the current time (as well as displaying a digital readout

Justin Reusch 2 Jan 29, 2022