3

I am using XCode 4.2 to develop an iPhone App , I am new to App development

I have the following NSStrings

NSString *year;
NSString *month;
NSString *day;
NSString *hour;
NSString *minute;

how can I set an NSDate *date variable using those

Thanks

AWF4vk
  • 5,810
  • 3
  • 37
  • 70
user1051935
  • 579
  • 1
  • 10
  • 29

2 Answers2

5

Example:

NSString *year   = @"2011";
NSString *month  = @"1";
NSString *day    = @"2";
NSString *hour   = @"3";
NSString *minute = @"3";

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.year   = [year intValue];
dateComponents.month  = [month intValue];
dateComponents.day    = [day intValue];
dateComponents.hour   = [hour intValue];
dateComponents.minute = [minute intValue];

NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
NSLog(@"date: %@", date);

NSLog output:

date: 2011-01-02 08:03:00 +0000
zaph
  • 111,848
  • 21
  • 189
  • 228
0

You basically have to create one string that has all the fields necessary to create a date.

That is, something like:

NSString * dateString = [NSString dateWithFormat: @"%@-%@-%@ %@:%@", year, month, day, hour, minute];

You can then follow the solutions provided in this related question or this other related question to come up with your NSDate (and if these solutions don't explain things enough, you can easily do a search -- the question of "how to convert NSStrings to NSDates" comes up quite often here).

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215