GithubHelp home page GithubHelp logo

malcommac / swiftdate Goto Github PK

View Code? Open in Web Editor NEW
7.5K 118.0 757.0 27.18 MB

🐔 Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift.

License: MIT License

Swift 99.78% Ruby 0.18% Shell 0.04%
nsdate-category swiftdate date date-formatting date-time timezone nsdate swift

swiftdate's Introduction

SwiftDate

Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift.

What's This?

SwiftDate is the definitive toolchain to manipulate and display dates and time zones on all Apple platform and even on Linux and Swift Server Side frameworks like Vapor or Kitura.
Over 3 million of downloads on CocoaPods.

From simple date manipulation to complex business logic SwiftDate maybe the right choice for your next project.

  • Easy Date Parsing (custom formats, iso8601, rss & many more)
  • Easy Date Formatting even with colloquial formatter and 140+ supported languages
  • Easy math operations with time units (2.hours + 5.minutes...)
  • Intuitive components extraction (day, hour, nearestHour, weekdayNameShort etc.)
  • Derivated dates generation (nextWeek, nextMonth, nextWeekday, tomorrow...)
  • Over 20+ fine grained date comparison functions (isToday, isTomorrow, isSameWeek, isNextYear...)
  • Swift 4's Codable Support
  • Random dates generation
  • Fine grained date enumeration functions
  • Time period support
  • Convert TimeIntervals to other units (2.hours.toUnits(.minutes))

and of course...

  • IT'S TESTED!. As 5.x the project has 90% of code coverage (want help us? write some unit tests and make a PR)
  • IT'S FULLY DOCUMENTED!, both with a complete guide and with Jazzy!
  • WE LOVE PLAYGROUND! Check out our interactive playground!

Start with SwiftDate

The entire library is fully documented both via XCode method inspector and a complete markdown documentation you can found below.

Explore SwiftDate

From simple date manipulation to complex business logic SwiftDate maybe the right choice for your next project.

Let me show to you the main features of the library:

SwiftDate can recognize all the major datetime formats automatically (ISO8601, RSS, Alt RSS, .NET, SQL, HTTP...) and you can also provide your own formats. Creating a new date has never been so easy!

// All default datetime formats (15+) are recognized automatically
let _ = "2010-05-20 15:30:00".toDate()
// You can also provide your own format!
let _ = "2010-05-20 15:30".toDate("yyyy-MM-dd HH:mm")
// All ISO8601 variants are supported too with timezone parsing!
let _ = "2017-09-17T11:59:29+02:00".toISODate()
// RSS, Extended, HTTP, SQL, .NET and all the major variants are supported!
let _ = "19 Nov 2015 22:20:40 +0100".toRSS(alt: true)

Date can be manipulated by adding or removing time components using a natural language; time unit extraction is also easy and includes the support for timezone, calendar and locales!

Manipulation can be done with standard math operators and between dates, time intervals, date components and relevant time units!

// Math operations support time units
let _ = ("2010-05-20 15:30:00".toDate() + 3.months - 2.days)
let _ = Date() + 3.hours
let _ = date1 + [.year:1, .month:2, .hour:5]
let _ = date1 + date2
// extract single time unit components from date manipulation
let over1Year = (date3 - date2).year > 1

SwiftDate include an extensive set of comparison functions; you can compare two dates by granularity, check if a date is an particular day, range and practically any other comparison you ever need.

Comparison is also available via standard math operators like (>, >=, <, <=).

// Standard math comparison is allowed
let _ = dateA >= dateB || dateC < dateB

// Complex comparisons includes granularity support
let _ = dateA.compare(toDate: dateB, granularity: .hour) == .orderedSame
let _ = dateA.isAfterDate(dateB, orEqual: true, granularity: .month) // > until month granularity
let _ = dateC.isInRange(date: dateA, and: dateB, orEqual: true, granularity: .day) // > until day granularity
let _ = dateA.earlierDate(dateB) // earlier date
let _ = dateA.laterDate(dateB) // later date

// Check if date is close to another with a given precision
let _ = dateA.compareCloseTo(dateB, precision: 1.hours.timeInterval

// Compare for relevant events:
// .isToday, .isYesterday, .isTomorrow, .isWeekend, isNextWeek
// .isSameDay, .isMorning, .isWeekday ...
let _ = date.compare(.isToday)
let _ = date.compare(.isNight)
let _ = date.compare(.isNextWeek)
let _ = date.compare(.isThisMonth)
let _ = date.compare(.startOfWeek)
let _ = date.compare(.isNextYear)
// ...and MORE THAN 30 OTHER COMPARISONS BUILT IN

// Operation in arrays (oldestIn, newestIn, sortedByNewest, sortedByOldest...)
let _ = DateInRegion.oldestIn(list: datesArray)
let _ = DateInRegion.sortedByNewest(list: datesArray)

You can create new dates from a string, time intervals or using date components. SwiftDate offers a wide set of functions to create and derivate your dates even with random generation!

// All dates includes timezone, calendar and locales!
// Create from string
let rome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let date1 = DateInRegion("2010-01-01 00:00:00", region: rome)!

// Create date from intervals
let _ = DateInRegion(seconds: 39940, region: rome)
let _ = DateInRegion(milliseconds: 5000, region: rome)

// Date from components
let _ = DateInRegion(components: {
	$0.year = 2001
	$0.month = 9
	$0.day = 11
	$0.hour = 12
	$0.minute = 0
}, region: rome)
let _ = DateInRegion(year: 2001, month: 1, day: 5, hour: 23, minute: 30, second: 0, region: rome)

// Random date generation with/without bounds
let _ = DateInRegion.randomDate(region: rome)
let _ = DateInRegion.randomDate(withinDaysBeforeToday: 5)
let _ = DateInRegion.randomDates(count: 50, between: lowerLimitDate, and: upperLimitDate, region: rome)

Date can be also generated starting from other dates; SwiftDate includes an extensive set of functions to generate. Over 20 different derivated dates can be created easily using dateAt() function.

let _ = DateInRegion().dateAt(.endOfDay) // today at the end of the day
// Over 20 different relevant dates including .startOfDay,
// .endOfDay, .startOfWeek, .tomorrow, .nextWeekday, .nextMonth, .prevYear, .nearestMinute and many others!
let _ = dateA.nextWeekday(.friday) // the next friday after dateA
let _ = (date.dateAt(.startOfMonth) - 3.days)
let _ = dateA.compare(.endOfWeek)

// Enumerate dates in range by providing your own custom
// increment expressed in date components
let from = DateInRegion("2015-01-01 10:00:00", region: rome)!
let to = DateInRegion("2015-01-02 03:00:00", region: rome)!
let increment2 = DateComponents.create {
	$0.hour = 1
	$0.minute = 30
	$0.second = 10
}
// generate dates in range by incrementing +1h,30m,10s each new date
let dates = DateInRegion.enumerateDates(from: fromDate2, to: toDate2, increment: increment2)

// Get all mondays in Jan 2019
let mondaysInJan2019 = Date.datesForWeekday(.monday, inMonth: 1, ofYear: 2019)

// Altering time components
let _ = dateA.dateBySet(hour: 10, min: 0, secs: 0)

// Truncating a date
let _ = dateA.dateTruncated(at: [.year,.month,.day]) // reset all time components keeping only date

// Rounding a date
let _ = dateA.dateRoundedAt(.toMins(10))
let _ = dateA.dateRoundedAt(.toFloor30Mins)

// Adding components
let _ = dateA.dateByAdding(5,.year)

// Date at the start/end of any time component
let _ = dateA.dateAtEndOf(.year) // 31 of Dec at 23:59:59
let _ = dateA.dateAtStartOf(.day) // at 00:00:00 of the same day
let _ = dateA.dateAtStartOf(.month) // at 00:00:00 of the first day of the month

You can extract components directly from dates and it includes the right value expressed in date's region (the right timezone and set locale!).

// Create a date in a region, London but with the lcoale set to IT
let london = Region(calendar: .gregorian, zone: .europeLondon, locale: .italian)
let date = DateInRegion("2018-02-05 23:14:45", format: dateFormat, region: london)!

// You can extract any of the all available time units.
// VALUES ARE EXPRESSED IN THE REGION OF THE DATE (THE RIGHT TIMEZONE).
// (you can still get the UTC/absolute value by getting the inner's absoluteDate).

let _ = date.year // 2018
let _ = date.month // 2
let _ = date.monthNameDefault // 'Febbraio' as the locale is the to IT!
let _ = date.firstDayOfWeek // 5
let _ = date.weekdayNameShort // 'Lun' as locale is the to IT
// ... all components are supported: .year, .month, .day, .hour, .minute, .second,
// .monthName, .weekday, .nearestHour, .firstDayOfWeek. .quarter and so on...

You can easily convert any date to another region (aka another calendar, locale or timezone) easily! New date contains all values expressed into the destination reason

// Conversion between timezones is easy using convertTo(region:) function
let rNY = Region(calendar: Calendars.gregorian, zone: Zones.americaNewYork, locale: Locales.english)
let rRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let dateInNY = "2017-01-01 00:00:00".toDate(region: rNY)
let dateInRome = dateInNY?.convertTo(region: rRome)!
print(dateInRome.toString()) // "dom gen 01 06:00:00 +0100 2017\n"

// You can also convert single region's attributes
let dateInIndia = dateInNY?.convertTo(timezone: Zones.indianChristmas, locale: Locales.nepaliIndia)
print("\(dateInIndia!.toString())") // "आइत जनवरी ०१ १२:००:०० +0700 २०१७\n"

Date formatting is easy, you can specify your own format, locale or use any of the provided ones.

// Date Formatting
let london = Region(calendar: .gregorian, zone: .europeLondon, locale: .english)
let date = ... // 2017-07-22T18:27:02+02:00 in london region
let _ = date.toDotNET() // /Date(1500740822000+0200)/
let _ = date.toISODate() // 2017-07-22T18:27:02+02:00
let _ = date.toFormat("dd MMM yyyy 'at' HH:mm") // "22 July 2017 at 18:27"

// You can also easily change locale when formatting a region
let _ = date.toFormat("dd MMM", locale: .italian) // "22 Luglio"

// Time Interval Formatting as Countdown
let interval: TimeInterval = (2.hours.timeInterval) + (34.minutes.timeInterval) + (5.seconds.timeInterval)
let _ = interval.toClock() // "2:34:05"

// Time Interval Formatting by Components
let _ = interval.toString {
	$0.maximumUnitCount = 4
	$0.allowedUnits = [.day, .hour, .minute]
	$0.collapsesLargestUnit = true
	$0.unitsStyle = .abbreviated
} // "2h 34m"

Relative formatting is all new in SwiftDate; it supports 120+ languages with two different styles (.default, .twitter), 9 flavours (.long, .longTime, .longConvenient, .short, .shortTime, .shortConvenient, .narrow, .tiny, .quantify) and all of them are customizable as you need. The extensible format allows you to provide your own translations and rules to override the default behaviour.

// Twitter Style
let _ = (Date() - 3.minutes).toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.english) // "3m"
let _ = (Date() - 6.minutes).toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.italian) // "6 min fa"

// Default Style
let _ = (now2 - 5.hours).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.english) // "5 hours ago"
let y = (now2 - 40.minutes).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.italian) // "45 minuti fa"

Both DateInRegion and Region fully support the new Swift's Codable protocol. This mean you can safely encode/decode them:

// Encoding/Decoding a Region
let region = Region(calendar: Calendars.gregorian, zone: Zones.europeOslo, locale: Locales.english)
let encodedJSON = try JSONEncoder().encode(region)
let decodedRegion = try JSONDecoder().decode(Region.self, from: encodedJSON)

// Encoding/Decoding a DateInRegion
let date = DateInRegion("2015-09-24T13:20:55", region: region)
let encodedDate = try JSONEncoder().encode(date)
let decodedDate = try JSONDecoder().decode(DateInRegion.self, from: encodedDate)

SwiftDate integrates the great Matthew York's DateTools module in order to support Time Periods.

See Time Periods section of the documentation.

swiftdate's People

Contributors

aki-mizu avatar akuraru avatar baryon avatar bitomule avatar codingrhythm avatar ehuynh avatar fhisa avatar hout avatar ilandbt avatar ipedro avatar kisukpark avatar lammertw avatar makesource avatar malcommac avatar marknorgren avatar maximusmccann avatar mojtabahs avatar onekiloparsec avatar pmusolino avatar rkreutz-teamwork avatar romanpodymov avatar rynecheow avatar sam-spencer avatar sammygutierrez avatar simonrice avatar stormxx avatar suprie avatar toriaezunama avatar volodg avatar ya-s-u avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swiftdate's Issues

Day of Week Manipulations

First of all, thank you for the quality library! My date manipulations in Swift not only look more pleasant to read, but they even sound better when reading them to my workmates!

This is just a small addition suggestion - one feature I've had to extend on my own is getting at the beginning and end of the week, based on the current calendar's start of week. I did this in my own codebase by making a public/internal property-based version of firstWeekDate() in an extension of NSDate. I know there is firstDayOfWeek & lastDayOfWeek, but the start/end of the week may not be in the same month (or year!). You could take this suggestion further by adding a function that returns the next / previous occurring day of the week - e.g., next(.Monday) or last(.Tuesday).

Region has no defaultRegion

I have added SwiftDate through carthage, which is now working on version 2.0.1, and have added an import SwiftDate line to the top of my Swift file that i'm working in. But when I try to use the defaultRegion() static method, I get a compiler error.

Any help is much appreciated.

screen shot 2015-12-01 at 8 18 48 pm

startOf and endOF func

Hi,

Playing with the idea to use an NSCalendarUnit hare as in:

let date = oldDate.endOf(.Day)

What do you think?

Support for relative/pretty date formatting

Is there the way to custom time unit when call the function like toRelativeString? , and then return the relative representation with custom time unit.
For example if the time unit is day, a relative representation of the date by comparing 2015-11-15 00:00 to the 2015-11-16 02:00 should be returned 1 day, and if the time unit is hour, should be returned 26 hours.

What do I import?

At the top of my code, what do I import to use this library after I've done the cocoa pods install?

Operators doesn't work

I want to use

date+1.months

But I get an:

Binary operator '+' cannot be applied to operators of type 'NSDate' and 'MonthCalendarType'

I'm on Swift 1.2

dateAtWeekStart returns different dates depending on the language

In enUS region, dateAtWeekStart returns the Sunday of the current week, but that's not the week start in all cases. For example, in Spain the Sunday is the last day of the week, and thus, dateAtWeekStart returns the next Sunday (7 days later). To make it consistent, it should always return the same date (previous sunday) or return the first day of the week in the current calendar (previous sunday or previous monday), but never a date in the future.

It could be easily fixed changing the method from:

func dateAtWeekStart() -> NSDate {
    let flags : NSCalendarUnit = [NSCalendarUnit.Year,NSCalendarUnit.Month ,
        NSCalendarUnit.WeekOfYear,
        NSCalendarUnit.Weekday]
    let components = NSCalendar.currentCalendar().components(flags, fromDate: self)
    components.weekday = 1 // Sunday
    components.hour = 0
    components.minute = 0
    components.second = 0
    return NSCalendar.currentCalendar().dateFromComponents(components)!
}

to:

    // Return the immediate previous Sunday regardless of the calendar
func dateAtWeekStart() -> NSDate {
    let flags : NSCalendarUnit = [NSCalendarUnit.Year,NSCalendarUnit.Month ,
        NSCalendarUnit.WeekOfYear,
        NSCalendarUnit.Weekday]
    let components = NSCalendar.currentCalendar().components(flags, fromDate: self)
    components.weekday = 2 // Monday
    components.hour = 0
    components.minute = 0
    components.second = 0
    return NSCalendar.currentCalendar().dateFromComponents(components)! - 1.day
}

or even better:

// Return the first day of the week of the current calendar
func dateAtWeekStart(firstWeekday: Int = NSCalendar.currentCalendar().firstWeekday) -> NSDate {
    let flags : NSCalendarUnit = [NSCalendarUnit.Year,
        NSCalendarUnit.WeekOfYear,
        NSCalendarUnit.Weekday]
    let components = NSCalendar.currentCalendar().components(flags, fromDate: self)
    components.weekday = firstWeekday
    components.hour = 0
    components.minute = 0
    components.second = 0
    return NSCalendar.currentCalendar().dateFromComponents(components)!
}

Carthage Bootstrap Error

Just tried to integrate SwiftDate through Carthage, and hit this error after running carthage update:

xcodebuild: error: Scheme SwiftDate-iOS is not currently configured for the build action.

Rounding option in toRelativeString

Would it be possible to add a rounding option to toRelativeString?
For example if maxUnits parameter is set to 1, the output for a date 1 hour 55 ago minutes is "1 hour". In some (maybe even most) cases it would make more sense to round the output to "2 hours".

Append "th", "st", "nd" or "rd" to day

It would be nice to have a feature that appends "th", "st", "nd" or "rd" to the day of date. Examples:

05th August, 01st December, 2nd February or 03rd July

version number no longer complies with ITC

if we branch from the current Head and submit to iTunes connect, it fails because of the versioning numbers being used in the pod. Details for this issue can be found here:

CocoaPods/CocoaPods#4421 (comment)

ITC is now enforcing version numbers of the format x.y.z

In my own app I was able to skirt this issue by not pulling from Head (pod 'SwiftDate', :head
), whatever version number shows up in the current release still conforms to ITC while what is showing up from head does not.

Thread-safe date formatter

When handling multiple threads, the shared date formatter can provide a result different than expected due to one thread having a different date_format than another one and being performed at the same time.

the result of "toRelativeString" can be returned in chinese?

let string = date.toRelativeString(fromDate: nil, abbreviated: false, maxUnits:2)
This example tell to SwiftDate to return a relative representation of the date by comparing it to the current date (nil in fromDate means NSDate()) without using an abbreviated form (use "seconds" not "secs", or "years" not "ys") and with a max number of units of 2 (this is used to get the approximation units to print, ie "2 hours, 30 minutes" are 2 units, "2 hours, 30 minutes, 5 seconds" are 3 units).

the result of "toRelativeString" can be returned in chinese? example: 2分钟

Manage time intervals and check if date fall in an interval

Hey there,

I don't have time to create a PR right now, but thought I'd post my code here for you to update. The isInTimeRange function on line 639 isn't working properly.

Here's the modified version that works for me:

func isInTimeRange(minTime: String!, maxTime: String!, format: String?) -> Bool {
        /*let dateFormatter = NSDate.localThreadDateFormatter()
        dateFormatter.dateFormat = format ?? "HH:mm"
        dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
        let minTimeDate = dateFormatter.dateFromString(minTime)
        let maxTimeDate = dateFormatter.dateFromString(maxTime)*/

        let minArray = minTime.componentsSeparatedByString(":")
        let minTimeDate = NSDate().set(componentsDict: ["hour":Int(minArray[0])!, "minute":Int(minArray[1])!])

        let maxArray = maxTime.componentsSeparatedByString(":")
        let maxTimeDate = NSDate().set(componentsDict: ["hour":Int(maxArray[0])!, "minute":Int(maxArray[1])!])

        if minTimeDate == nil || maxTimeDate == nil {
            return false
        }
        let inBetween = (self.compare(minTimeDate!) == NSComparisonResult.OrderedDescending &&
            self.compare(maxTimeDate!) == NSComparisonResult.OrderedAscending)

        print("minTimeDate: \(minTimeDate)")
        print("maxTimeDate: \(maxTimeDate)")
        print("current: \(self)")

        return inBetween
    }

Basically I had to make sure that I create the new NSDate objects and set them to todays date. Your existing way was setting it to whatever the start date of the unix epoch time is again.

I can submit a PR over the next few days or so, unless you have time to just take the above code and maybe clean it up a bit yourself.

Thanks for the lib btw! :)

DateFormatter object from NSDate.cachedObjectInCurrentThread is modified causing different return results from some functions.

Hello,

Thank you for this excellent library. It certainly does make working with dates quite a bit more pleasant.

Ran into an issue where calling .toISOString() changes the dateFormatter timezone and date format from the default/cached dateFormetter. Subsequent calls to .toShortString(), for example, ends up using the modified dateFormatter from .toISOString() resulting in unexpected short/medium/long string prints of the time now based on UTC instead of the user's local timezone.

Once suggestion is to always set the dateFormatter defaults each time the dateFormatter object is retrieved or make sure each func that modifies the cachedDateFormatter returns it back to the "found" state.

Wes

New Release Tag

Swift2.0 & Carthage are supported now.
I would like the new release tag for the version.

create nsdate object is not working?

Hello, thanks for your library, but i got a bug when i tried the things below
let tempDate = NSDate.date(fromString: "22/01/2015", format: DateFormat.Custom("DD/MM/YYYY"))
print(tempDate)

the result is:
Optional(2014-12-21 05:00:00 +0000)

Substract 1 month doesn't work

I'm trying to use this operator

public func - (left: NSDate, right: CalendarType) -> NSDate {
    let calendarType = right.copy()
    calendarType.amount = -calendarType.amount
    let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    return calendar.dateByAddingComponents(calendarType.dateComponents(), toDate: left, options: NSCalendarOptions.allZeros)!
}

but always return the same month usin:

date = date-1.months

Edit: It returns the same month with any amount.

Edit2:

date.add("month",value:-1)

doesn't work too but I don't see why

Wrong display on actual device

On simulator, I am getting the proper display of about 1 day ago.

Upon moving to the device, I am getting the wrong display of about 9.223372e+18 wks ago.

toRelativeString fails on ios 8 / swift 1.2

toRelativeString returns an unexpected value on devices running iOS 8+

This seems to be the offending line:

let unitList : [String] = ["year", "month", "week", "day", "hour", "minute", "second"]

This is likely due to the deprecation of the "week" property for NSDateComponents.

https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDateComponents_Class/index.html

Changing to "weekOfYear" seems to have fixed things, but a nice check would be good to have in place to cover all bases and have a more reliable backwards compatibility.

Not able to archive

Hi, I am not able to archive. Also tried with ExampleProject.

Error : Command failed due to signal: Segmentation fault: 11

0 swift 0x0000000111a8337b llvm::sys::PrintStackTrace(sFILE) + 43
1 swift 0x0000000111a83abb SignalHandler(int) + 379
2 libsystem_platform.dylib 0x00007fff9497552a sigtramp + 26
3 libsystem_platform.dylib 0x0000000000000010 sigtramp + 1802021632
4 swift 0x000000011128554a llvm::DwarfCompileUnit::applyVariableAttributes(llvm::DbgVariable const&, llvm::DIE&) + 74
5 swift 0x000000011128a318 llvm::DwarfDebug::finishVariableDefinitions() + 376
6 swift 0x000000011128a67e llvm::DwarfDebug::finalizeModuleInfo() + 126
7 swift 0x000000011128a9b4 llvm::DwarfDebug::endModule() + 52
8 swift 0x0000000111270b9a llvm::AsmPrinter::doFinalization(llvm::Module&) + 554
9 swift 0x00000001118f5f7b llvm::FPPassManager::doFinalization(llvm::Module&) + 59
10 swift 0x00000001118f6487 llvm::legacy::PassManagerImpl::run(llvm::Module&) + 1207
11 swift 0x000000010fc7a8ce performLLVM(swift::IRGenOptions&, swift::DiagnosticEngine&, llvm::sys::SmartMutex
, llvm::Module
, llvm::TargetMachine
, llvm::StringRef) + 1454
12 swift 0x000000010fc7ab01 swift::performLLVM(swift::IRGenOptions&, swift::ASTContext&, llvm::Module_) + 145
13 swift 0x000000010fb747f5 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef, int&) + 501
14 swift 0x000000010fb743f3 frontend_main(llvm::ArrayRef<char const*>, char const_, void_) + 2691
15 swift 0x000000010fb70a74 main + 2324
16 libdyld.dylib 0x00007fff94ad85ad start + 1
17 libdyld.dylib 0x0000000000000010 start + 1800567396

problem with pod

Hi I installed the library with a pod file and could not use it only when I imported the file itself to the project using Xcode 7.
is there a known issue? solution?

Thanks,
Gal

date.toString format

From doc:
let string = date.toString(format: DateFormat.Custom("YYYY-MM-DD")) // something like "2015-01-01"

but if date 2015-02-01
let string = date.toString(format: DateFormat.Custom("YYYY-MM-DD")) // something like "2015-01-32"

firstDayOfWeek and lastDayofWeek incorrect results

I am +2 GMT zone. For today, the first day of week shows as 10 (sunday) which is incorrect. the last day shows as 17 (sunday). If firstdayofweek is 10 then the lastdayofweek should be 16. The firstdayofweek for my computer is 11 and the last day is 17 (monday is the first day of week).

screen shot 2015-05-13 at 12 33 53

Command failed due to signal: Segmentation fault: 11

screen shot 2015-10-05 at 3 27 30 pm
Am getting this error: "Command failed due to signal: Segmentation fault: 11" when trying to run test suite on my project. Am using SwiftDate via CocoaPods. Am using few other libraries but only SwiftDate is causing this crash. For build & run, though it runs fine.

toRelativeString error on Phone

Hello there,

This code seems to work fine on the simulator, but on my phone I get an error
cell.ageLabel.text = object.published_at.toRelativeString(fromDate: NSDate(), abbreviated: true, maxUnits: 1)
println("object published \(object.published_at) age label \(cell.ageLabel.text) and date \(NSDate())")

outputs on phone
object published 2015-06-11 15:34:56 +0000 age label Optional("9.223372e+18w") and date 2015-06-13 22:29:15 +0000

outputs on simulator
object published 2015-06-11 15:34:56 +0000 age label Optional("2 days ago") and date 2015-06-13 22:41:17 +0000

Any tips?

Set on class

What about a class func?

let date1 = NSDate.set(yearForWeekOfYear: 2014, weekOfYear: 23, weekDay: 3)
let date2 = NSDate.set(year 2014, month: 10, day: 3)
let date3 = NSDate.set(year 2014, quarter: 3, month: 1, day: 3)
let date4 = NSDate.set(year 2014, month: 1, weekInMonth: 2, day: 3)
let date5 = NSDate.set(year 2014, month: 1, weekInMonth: 2, day: 3, hour: 12, minute: 3)

2.0 not pushed to cocoapods

Hey, would you mind pushing the latest podspec up to cocoapods trunk? Can't install version 2.0 via cocoapods until it's updated.

Make code for autoUpdate self explanatory

A new calendar type can be initialised with let calType = CalendarType.Local(true) of which functionality is unclear at first sight.
Better: let calType = CalendarType.Local and let calType = CalendarType.AutoUpdatingLocal
In addition: the current calendar is named current and not local for a reason: it is not location related but user related. if I take my European iPhone to China, the local calendar will be Chinese but my calendar will stay Gregorian (if I choose to do so).
So even better: let calType = CalendarType.Current and let calType = CalendarType.AutoUpdatingCurrent
Alternatively, if you insist on the Bool parameter: let calType = CalendarType.CurrentWithAutoUpdate(false)

how to parse [AnyObject] ?

if let dataArray = json["data"].arrayObject {

for item in dataArray {
let name = item["name"]
}
}

not woking item didnt have subscript string

if let dataArray = json["data"].array {

for item in dataArray {
let name = item["name"] // cant get value
}
}

wrong place

Misunderstanding how date components works with timezone and time calculations

First, thank you for good library.

I am very stupid with dates, maybe you can explain me what i miss.

let justDate = NSDate()
let localDate = NSDate().toLocalTime()
let hongkongDate = NSDate().toTimezone("HKT")!
let westEurDate = NSDate().toTimezone("MSK")!
let futureDate = justDate + 4.hour

L.d("justDate: \(justDate) (\(justDate.hour) : \(justDate.minute))")
L.d("localDate: \(localDate) (\(localDate.hour) : \(localDate.minute))")
L.d("hongkongDate: \(hongkongDate) (\(hongkongDate.hour) : \(hongkongDate.minute))")
L.d("westEurDate: \(westEurDate) (\(westEurDate.hour) : \(westEurDate.minute))")
L.d("futureDate: \(futureDate) (\(futureDate.hour) : \(futureDate.minute))")

Output is strange for me.

justDate: 2015-10-20 18:53:47 +0000 (21 : 53)
localDate: 2015-10-20 15:53:47 +0000 (18 : 53)
hongkongDate: 2015-10-21 02:53:47 +0000 (5 : 53)
westEurDate: 2015-10-20 21:53:47 +0000 (0 : 53)
futureDate: 2015-10-20 22:53:47 +0000 (1 : 53)

This code was run on iPhone, not simulator. Real local time in time zone MSK was 21:53

Minutes are save in every case. Hours different, but has wrong values, as i see.

The target of this experiment is get hours and minutes of date in specific timezone.

What i am doing wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.