0

I have NSString with value "29/01/2010" Which I want to convert into NSDate with replacing the year value with the current year.

For that I have tried with

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:2013];
    [components setMonth:01];
    [components setDay:29];
    NSLog(@"%@",[calendar dateFromComponents:components]);

Result it gives is 2013-01-28 18:30:00 +0000

Another way tried with is

     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy"];
    NSString *yearString = [formatter stringFromDate:[NSDate date]];

    NSArray *dateComponents = [aStrBirthDate componentsSeparatedByString:@"/"];
    aStrBirthDate = [aStrBirthDate stringByReplacingOccurrencesOfString:[dateComponents lastObject] withString:yearString];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:aStrBirthDate];

This also gives the same result 2013-01-28 18:30:00 +0000

Heena
  • 2,348
  • 3
  • 32
  • 58
  • The line is not needed and leaking if not in ARC: `NSDate *dateFromString = [[NSDate alloc] init];` just do `NSDate *dateFromString = [dateFormatter dateFromString:aStrBirthDate];` – rckoenes Jul 04 '13 at 10:45
  • @rckoenes, I am using ARC.So this statement will not leak – Heena Jul 04 '13 at 10:53
  • @Abizern, I tried with answer in suggested question ` [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];` but still its not working. It is giving weird and wrong date as `1726785-05-06 00:00:00 +0000` – Heena Jul 04 '13 at 10:55
  • 1
    @Roshni: NSLogging a NSDate always prints the date with respect to GMT. There must be many answers containing that information. See for example http://stackoverflow.com/a/6229695/1187415 or http://stackoverflow.com/a/4547607/1187415. – Martin R Jul 04 '13 at 11:03
  • @Roshni still it is not correct, you are create an instance of an object just to replace it with an other the next line. It just bad coding. – rckoenes Jul 04 '13 at 11:06

0 Answers0