Skip to main content

Getting the dayBefore and dayAfter from NSDate (in Swift)

So before I write part 2 of the story of how my first mobile(iOS) app came to be, this would be a small post on how to use Extensions in Swift, to make code more readable...amongst other things.

Problem

So in my iOS app, there are a few places where I have to get the day before(yesterday) and the day after(tomorrow) for a date. 

Solution

In the first version of my code, I had the code such as this (Read on to find out a more correct solution for calculating dates)

For the day after
let oneDay:Double = 60 * 60 * 24
return self.dateByAddingTimeInterval(oneDay)
For the day before
let oneDay:Double = 60 * 60 * 24
return self.dateByAddingTimeInterval(-(Double(oneDay)))
one day has 24 hours, each hour has 60 mins and each minute has 60 seconds, so 60 * 60  * 24

to calculate the solution to my problem. This was working and it was all fine...until I delved deeper into Swift(by reading this ebook by Apple) and found out about Extensions!!! It was love at first write? (if there is such a thing) Extensions in Swift are awesome and you can have a read about the benefits of it here or follow this tutorial

Great! I am now in love with Extensions in Swift, but how does it help me?

Ok so using extension, all I need to do is add the following code in one of the Swift files in my iOS app project 
extension NSDate {
    var dayAfter:NSDate {
        let oneDay:Double = 60 * 60 * 24
        return self.dateByAddingTimeInterval(oneDay)
    }
    var dayBefore:NSDate {
        let oneDay:Double = 60 * 60 * 24
        return self.dateByAddingTimeInterval(-(Double(oneDay)))
    }
}
and, if I have an NSDate anywhere in my project, I can just find out the dayBefore or the dayAfter the NSDate object like this
let today = NSDate()
today.dayBefore
today.dayAfter
Awesome right?

The most correct solution for calculating dates (for iOS8)

Ok, so the main point of this post was really more about me yelling out how much I love Extensions in Swift. However since I have used date calculations as an example and similar logic exists in my app's code, I should make this right and include the correct solution. 

Now since writing this post i.e. one day ago, I started looking around a bit to find out how other's are going about solving this problem. During my search, I came across this post and realised one problem with the above date calculations. Here's a quote from Rob's answer in the post, indicating one problem with it,

"But I would advise against doing any manual adjustments of NSDate values by adjusting it by some time interval that is a multiple of the seconds per day (e.g. 24*60*60). That technique works fine if you're just adding some time interval, but for date calculations, you really want to use NSCalendar, to avoid problems stemming from daylight savings and the like." - Rob

So the code in this post to calculate dayBefore and dayAfter for the Extension on NSDate, should be something like the the code below. Please note that the code below would only work on iOS8 and above, so if you have a device running an earlier iOS version, it is not going to work.


extension NSDate {
    var dayAfter:NSDate {
        let calendar =  NSCalendar(calendarIdentifier: NSGregorianCalendar)!
        return calendar.dateByAddingUnit(.CalendarUnitDay, value: 1, toDate: self, options: nil)!

    }
    var dayBefore:NSDate {
        let calendar =  NSCalendar(calendarIdentifier: NSGregorianCalendar)!
        return calendar.dateByAddingUnit(.CalendarUnitDay, value: -1, toDate: self, options: nil)!
    }
}

Lastly, I am working on my startup full-time right now, so if you find my blogposts useful and want to see me share more useful stuff in the future, please do support me. You can support me, 

Whichever version you try please leave us a review. An app store review from you would really help us.

Comments

Popular posts from this blog

Upload to AWS S3 from Java API

In this post, you will see code samples for how to upload a file to AWS S3 bucket from a Java Spring Boot app. The code you will see here is from one of my open-source repositories on Github, called document-sharing. Problem Let’s say you are building a document sharing app where you allow your users to upload the file to a public cloud solution. Now, let’s say you are building the API for your app with Spring Boot and you are using AWS S3 as your public cloud solution. How would you do that? This blog post contains the code that can help you achieve that. Read more below,  Upload to AWS S3 bucket from Java Spring Boot app - My Day To-Do (mydaytodo.com)

Addressing app review rejections for auto-renewing subscription in-app purchase (iOS)

The ability to know what the weather is like while planning your day is a feature of  My Day To-Do  Pro and as of the last update it’s also a part of the  Lite version . Unlike the Pro version it’s an auto-renewing subscription based  in-app purchase (IAP)  in the Lite version. What means is that when a user purchases it, the user only pays for the subscription duration after which the user will be automatically charged for the next period. Adding an  auto-renewing  subscription based IAP proved to be somewhat challenging in terms of the app store review i.e. the app update was rejected by the App Review team thrice because of missing information about the IAP. Therefore in this post I will share my experiences and knowledge of adding auto-renewing IAP in hopes to save someone else the time that I had to spend on this problem. In-App purchase This year I started adding IAPs to My Day To-Do Lite which lead to learning about different types of IAP...

Serving HTML content in an iOS app that works in iOS 7 and later (using Swift)

As I have mentioned in an earlier post , I really enjoying coding in Swift. Now what am I doing with it? Well I am trying to build an HTML5 app that must work on devices with iOS 7. So in iOS8 apple has introduced a whole bunch of features that facilitate easy communication between web content and lets just call it back-end Swift code, but those features are not in iOS 7. So why do I want to build something that would work in an older OS? well I do not expect existing iOS users to upgrade to iOS 8 straight away and i also know a couple of people who would be very reluctant to upgrade their iPhones to iOS 8. Now in case you do not, you can have a read of the "Working with WebViews" section of this post , to know how to serve HTML content with WebViews. So when I started building my app, I wanted to know: How do I invoke some Swift code from my HTML content? Well the solution to this may feel a little bit "hacky" but it is a solution to achieve this.  The followi...