NSDateComponents value printed out different


#1

when i was attempting the challenge, i notice that the hour that i set is different from when the one i set. After investigation, i noticed it differs from the timezone i and in. Currently, i am in a +8 GMT/UTC time zone.

i wrote the following code

[code]NSDateComponents *comps = [[NSDateComponents alloc]init];
[comps setYear:2014];
[comps setMonth:3];
[comps setDay:31];
[comps setHour:8];
[comps setMinute:0];
[comps setSecond:0];

    NSCalendar *g = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *dateOfBirth = [g dateFromComponents:comps];
    NSLog(@"Birthdate is %@",dateOfBirth);

[/code]

This is the output of NSLog.

“Birthdate is 2014-03-31 00:00:00 +0000”

I am wondering how do i change the timezone to my local time zone.
Thanks!


#2

Here is one way:

NSLog (@"Birthdate is %@", [dateOfBirth descriptionWithLocale:[NSLocale currentLocale]]);

You can also use a NSDateFormatter object to do custom date and time formatting:

// Print current date and time

// ---------------------------------------------------------------------------------------
//
// Courtesy of Pretty Function - www.pretty-function.org

// ---------------------------------------------------------------------------------------
//
#import <Foundation/Foundation.h>

NSString *currentDateAndTime ();

// ---------------------------------------------------------------------------------------
//
int main (int argc, const char * argv[])
{
    @autoreleasepool
    {
        NSLog (@"Current time: %@", currentDateAndTime());
    }
    return 0;
}

// ---------------------------------------------------------------------------------------
//
NSString *currentDateAndTime ()
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    
    [dateFormatter setLocale:[NSLocale currentLocale]];
    
    NSDate *date = [NSDate date];

    return [dateFormatter stringFromDate:date];
}