Search code examples
xcode4nsdate

wrong time give while executing the code


I'm creating a simple alarm clock app. The problem is that i get the wrong output dates in the logs and I don't know why. Please try to resolve my problem. Below is my code:

Following code is use into the init method then is work properly while i use following code into my viewdidLoad then it's not work

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// Get the current date
NSDate *pickerDate = [self.datePicker date];

// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) 
                                               fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) 
                                               fromDate:pickerDate];


NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];

[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
        NSLog(@"date components are:>>%@",dateComps);
NSLog(@"Item date is ::>>%@",itemDate);


[dateComps release];

In that while the print object than it shows the wrong date and timezone issue aries here. Please help to solve this problem

@samuel


Solution

  • after many search finding the reason for that

    When any date picked into pickerviewcontroller always that fives only +000 gmt format

    If the we need to convert date with the local time zone for that we need to use the dateformater class into the project for that below code for that.

    NSDateFormatter* df_local = [[NSDateFormatter alloc] init];
    [df_local setTimeZone:[NSTimeZone localTimeZone]];
    [df_local setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    // [df_local stringFromDate:date];
    
    NSString *strForArr=[self.arForSubTitle objectAtIndex:0];
    NSString *newStr = [strForArr substringToIndex:[strForArr length]-5];
    NSDate *theDate = [df_local dateFromString:newStr];        
    
    NSLog(@"%@",[theDate description]);
    

    Thanks and regards

    @samuel.