The easiest way to create an NSDate object is to create “right now” with our convenience method date: NSDate *myDate = [NSDate date]; But if you want to create a date object with a date such as your birthday it gets a little bit trickier, and – more importantly – much less obvious. To do […]
There was me thinking I’d have to whip out NSDateComponents and NSCalendar – but my mind works too complicated at times. All we need to do this is our good friend the NSDateFormatter and the Unicode Date Format MMMM – let’s check it out: // create today’s date NSDate *myDate = [NSDate date]; // create […]
Imagine you had an NSDate object and want to add days several to it. We can use NSDate method dateByAddingComponents for this, which takes – as you may have guessed – NSDateComponents as parameters. In this example, let’s assume we want to know what date it is 5 days from today: int daysToAdd = 5; […]
When you create new date using [NSDate date] (i.e. today, as in right now) your date will save the current time as well as its date. In fact, under the hood an NSDate object is the amount of seconds that have elapsed since the 1st of January 2001 (or 1970), in milliseconds. So really it’s […]
Imagine you had two NSDate objects and you’d like to find out the time interval between those dates. NSDate objects alone won’t help us out there unless we do some serious NSDateFormatting and hair pulling. Lucky for us there are a few other classes available that will help us do this, namely NSCalendar and NSDateComponents. […]
NSDate *date = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateStyle:NSDateFormatterLongStyle]; [dateFormatter setTimeStyle:NSDateFormatterLongStyle]; NSString *dateString = [dateFormatter stringFromDate:date]; First we’ll create a date object. Next we’ll create an NSDateFormatter and set how we’d like for display our date (and optionally our time). Then we’ll call the magical stringFromDate method which will create our string.
Hey Jay, Great Idea. Here’s a little snippet of code that grabs the current date, then using a couple of NSDateFormatter methods converts it to the current time.