100

Seems like a simple thing but I can't seem to find a way to do it.

It would be great to see a couple different methods.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
nickthedude
  • 4,925
  • 10
  • 36
  • 51

8 Answers8

217

@Chuck's answer is correct, and lead me to the following code. Thought I'd share:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:10];
[comps setMonth:10];
[comps setYear:2010];
NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:comps];
derpoliuk
  • 1,756
  • 2
  • 27
  • 43
Oded Ben Dov
  • 9,936
  • 6
  • 38
  • 53
21

You can use this

NSString *dateString = @"03-Sep-11";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd-MMM-yy";
NSDate *date = [dateFormatter dateFromString:dateString];

Hope this will help you out.

Kamleshwar
  • 2,967
  • 1
  • 25
  • 27
  • Be careful using the "dateFromString" function - I found that with some perfectly-valid dates, it'd fail miserably. See my post below for an alternative way of parsing date strings. – Mike Gledhill Jul 18 '13 at 14:19
  • The way Oded Ben mention is also another best way..... NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:10]; [comps setMonth:10]; [comps setYear:2010]; NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:comps]; – Kamleshwar Aug 12 '16 at 23:00
  • This code will fail if the app is localized to a language where the month name doesn't match. You should also use a 4-digit year to be clear. – HangarRash Aug 08 '23 at 05:48
17

If you're talking about a specific calendar date rather than a UNIXy date, you probably want NSCalendar's dateFromComponents:.

Chuck
  • 234,037
  • 30
  • 302
  • 389
12

Swift Examples

Examples are often the easiest way to learn. Here are a few examples.

Now

This one is the easiest.

let currentDateTime = Date()

February 20, 2017

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 2017
dateComponents.month = 2
dateComponents.day = 20

// Create date from components
let userCalendar = Calendar.current // user calendar
let dateThisPostWasUpdated = userCalendar.date(from: dateComponents)

April 1, 1976

// Specify date components
var dateComponents = DateComponents()
dateComponents.year = 1976
dateComponents.month = 4
dateComponents.day = 1

// Create date from components
let userCalendar = Calendar.current // user calendar
let appleFoundedDate = userCalendar.date(from: dateComponents)

Need more details...?

There are other ways to create dates, too. If you want to learn those, as well as how to display a date, then see my fuller answer.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
9

See the documentation for NSDate. You can use the dateFromString: method of NSDateFormatter or the dateFromComponents: method of NSCalendar.

zoul
  • 102,279
  • 44
  • 260
  • 354
  • I keep getting this date : "1969-12-31 16:00:00" -0800 when using date from string – nickthedude Apr 05 '10 at 17:51
  • NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; NSDate *capturedStartDate = [dateFormatter dateFromString: @"Jan 2, 2001"]; NSLog(@"%@", [capturedStartDate description]); output: 2010-04-05 10:49:47.688 Calendar2[21339:207] 1969-12-31 16:00:00 -0800 – nickthedude Apr 05 '10 at 17:52
  • Maybe you need to set some parameters on the date formatted instead of plain `init`? – zoul Apr 05 '10 at 18:09
4

I found this thread while looking for an answer to this question but then I found a good example in one my Big Nerd Ranch Objective-C Programming book. Credit to them, not me.

  NSDateComponents *myBDay  =[[NSDateComponents alloc] init];
    [myBDay setDay:22];
    [myBDay setMonth: 04];
    [myBDay setYear: 1984];
    [myBDay setHour:9];
    [myBDay setMinute:25];
    [myBDay setSecond:35];

    NSCalendar *g = [[ NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *dateOfBirth = [g dateFromComponents:myBDay];
Lev Chlumov
  • 126
  • 1
  • 2
2

It is ridiculous, isn't it ?

Mid-2013 and Apple still hasn't provided a simple way to set a NSDate value.

During my current iPad project, I couldn't believe I had to stop productivity for a while to write my own helper class to get the Year value from an NSDate. I mean, come on, this is basic stuff.

Anyway, here's the helper class I used in my project, to convert a string into an NSDate value :

@implementation DateHelper

+(NSDate*)parseDateString:(NSString *)dateString
{
    NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
    [rfc3339TimestampFormatterWithTimeZone setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"MMM dd, yyyy"];

    NSDate *theDate = nil;
    NSError *error = nil;
    if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) {
        NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
    }

    return theDate;
}

@end

Using this code, you could set an NSDate value using something like:

NSDate* date = [DateHelper parseDateString:@"Jul 16, 2013"];

Note: this function was based on code taken from here: https://stackoverflow.com/a/3968411/391605

My solution had been to use the following code, but I found that sometimes, it just wouldn't parse, and would return nil.

//  Take a date string in the format "Oct 23, 2013", and convert it into a NSDate value
//  THIS DOESN'T WORK !  DON'T TRUST THIS CODE !!
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM dd, yyyy"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate* date = [formatter dateFromString:dateString];

I remember it failed miserably on "Oct 12, 2012"... which is why I gave up and used the more complicated "parseDateString" function shown above.

My point is... be careful.

Some of the very-basic NSDate functions just don't work properly...

Community
  • 1
  • 1
Mike Gledhill
  • 27,846
  • 7
  • 149
  • 159
-1

I wrote this in Objective-C. It's not efficient but simple.

+(NSDate *) MakeNSDate : (int) year : (int) month : (int) day : (int) hour : (int) min : (int) sec
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSDate *dtRet = [dateFormatter dateFromString:[NSString stringWithFormat:@"%4d/%02d/%2d %02d:%02d:%02d", year, month, day, hour, min, sec]];
    return dtRet;
}
Hank Chang
  • 199
  • 2
  • 10