---
title: "NSDate operators"
slug: nsdate-operators
section: tech
date: 2016-04-29T14:23:00.000Z
canonical: https://roland.leth.ro/blog/tech/nsdate-operators
---

I personally find this a bit of a mouthful, especially if you have to type it a lot:

```swift
if someDate.compare(otherDate) == .OrderedAscending {
  // Do stuff
}
```

_Update, Oct 10, 2017: These are now built-in for `Date`. Leaving these here like they are (Swift 2), since the whole post is just about them._

But we can have a few operators to make our lives a bit easier:

```swift
func <(lhs: NSDate, rhs: NSDate) -> Bool {
	return lhs.compare(rhs) == .OrderedAscending
}

func <=(lhs: NSDate, rhs: NSDate) -> Bool {
	return lhs < rhs || lhs == rhs
}

func >(lhs: NSDate, rhs: NSDate) -> Bool {
	return lhs.compare(rhs) == .OrderedDescending
}

func >=(lhs: NSDate, rhs: NSDate) -> Bool {
	return lhs > rhs || lhs == rhs
}

func ==(lhs: NSDate, rhs: NSDate) -> Bool {
	return lhs.compare(rhs) == .OrderedSame
}

func !=(lhs: NSDate, rhs: NSDate) -> Bool {
	return !(lhs == rhs)
}
```

I think this is not only prettier and shorter, but a bit more expressive, as well:

```swift
if someDate < otherDate {
  // Do stuff
}
```
