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...

Getting started with iOS programming using Swift (Part 1)

I have not been too fond of Objective-C, which was the primary reason for me to stay away from making iOS apps till now. So what changed? Well Apple has done something very interesting recently and that is the introduction of a new programming language i.e. Swift. Swift is awesome, it almost feels like Python, C++ and Objective-C had a baby with some of their good parts in them. So I have been getting to know Swift and it is an awesome language to program in. What I am going to share with this and a series of blog posts are solutions to some problems that i have encounter while i am trying to finish my first iOS app. The one hurdle that I have encountered while getting started on developing an iOS app is that a majority of the solutions for iOS specific problems provide solutions to them using Objective-C. Which is fair, because Swift has not been around for that long. Anyway let us get started with a few basics, A few basics I would highly recommend having a read of this book...