Search code examples
objective-cnsdateformatterdate-formatting

How to convert date string to another format in Objective-C


I have a date picker that only adds date for that date I want to add time string and convert it to date.

fromString = @"00:00:00";
NSString *fromDate = [fromdate.text stringByAppendingString:@" "];
fromDate = [fromDate fromString];
NSDate *currentDate = [self dateFromString:fromDate withFormat:@"dd/MM/yyyy HH:mm:ss"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+5.30"]];
NSString *dateString = [dateFormatter stringFromDate: currentDate];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *date = [self dateFromString: dateString withFormat:@"dd/MM/yyyy HH:mm:ss"];
NSString *fromDate1 = [NSString stringWithFormat:@"/Date(%.0f000%@)/", [date timeIntervalSince1970],[formatter stringFromDate:date]];

My Problem is that I'm getting 5.30 extra time when converting to string.


Solution

  • My Problem is that I'm getting 5.30 extra time when converting to string.

    To convert from string initially you use:

    NSDate *CurrentDate = [self dateFromString:fROMDATE withFormat:@"dd/MM/yyyy HH:mm:ss"];
    

    You do not give the code for dateFromString but at a guess this routine is using the GMT/UTC time zone for the conversion.

    To convert back to a string you first do:

    [DATEFORMATER setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+5.30"]];
    

    And so if your original time was converted from a string as GMT your DATE_STRING will show a time 5.5 hours "later" (the same time point in GMT, just displayed as it is in the GMT+5.30 time zone).

    HTH