-1

I have dateString with this format "mm/dd/yyyy '-' HH:mm". I want to extract the date in string and hour in string. I've tried the following code but this return a wrong date:

- (void) extractDate: (NSString *)dateString intoHour: (NSString *)hourLabel and: (NSString*)dateLabel {
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"mm/dd/yyyy '-' HH:mm"];
    NSData *date = [formatter dateFromString:dateString];

    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:date];

    hourLabel = [NSString stringWithFormat:@"%lu:%lu", [components hour], [components minute]];
    dateLabel = [NSString stringWithFormat:@"%lu/%lu/%lu", [components day], [components month], [components year]];
}

Exemple String: "05/01/2015 - 11:15"

Result: date: 1/1/2015, time: 11:15 and also how can I maintain this date format dd/mm/yyyy, I mean when the day is 1, it shows 01

Haroun SMIDA
  • 1,106
  • 3
  • 16
  • 32
  • `MM` for the month, else wise it's minutes (as you used it already). NSNumberFormatter can use leading zero if needed. Or you can just use a `NSDateFormatter` from the date you got, instead of use `NSDateComponents`: `[formatter setDateFormat:@"MM/dd/yyyy"]; dateLabel = [formatter stringFromDate:date]; [formatter setDateFormat:@"HH:mm"]; hourLabel = [formatter stringFromDate:date];` By the way `hourLabel`/`dateLabel` as `NSString` and not `UILabel` is quite a misleading var naming. – Larme Mar 31 '16 at 16:14
  • You should use `NSDateFormatter` to do it. But for your interest, use `[NSString stringWithFormat:@"%02d", [components day]]` would do the job for you, – zc246 Mar 31 '16 at 16:19
  • How to use  `NSDateFormatter` to get each part in a string – Haroun SMIDA Mar 31 '16 at 16:37

1 Answers1

1

Not tested but:

MM for the month. Not mm which is minutes.

You already have a NSDateFormatter so why not use it again instead of NSDateComponents and NSString formats?

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"MM/dd/yyyy '-' HH:mm"];
NSDate *date = [formatter dateFromString:dateString];

//Now you have the correct date. So we'll use the NSDateFormatter to transform NSDate (date) into NSString according to the format we need.

[formatter setDateFormat:@"MM/dd/yyyy"];
dateLabel = [formatter stringFromDate:date];
[formatter setDateFormat:@"HH:mm"];
hourLabel = [formatter stringFromDate:date];

hourLabel/dateLabel as NSString and not UILabel is quite a misleading var naming.

Larme
  • 24,190
  • 6
  • 51
  • 81