Get a NSDate object already with local time zone applied


#1

Reading the other topics in this chapter, I have observed that a recurrent question is how to get a NSDate object already with local time zone applied.

Follow two methods to get current date and time with NSDate class:

  1. Send a message to the NSDate with the date class method:
  1. Send a nested message: one to NSDate class with the alloc class method and another to the object returned with the init instance method:

Both methods above get the current date and time in the GMT time zone.
But, I live in Brazil in a city with time zone GMT-3. How can I get a NSDate object with the offset of my local time zone already calculated?
Follow a very simple solution:

Follow a simple code to test all the code above and to verify that you will get the current date and time with the offset already calculated:

[code]//
// main.m
// Calendar
//
// Created by Rogério Moraes de Carvalho on 13/05/2012.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

@autoreleasepool {
	
	// Allocating and initializing two NSDate objects with the crrent date and time in the default GMT time zone.
	NSDate *currentDateTime1 = [NSDate date];
	NSDate *currentDateTime2 = [[NSDate alloc] init];
	
	NSLog(@"Current date and time 1: %@", currentDateTime1);
	NSLog(@"Current date and time 2: %@", currentDateTime2);
	
	NSDate *currentDateTimeWithOffset = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone] secondsFromGMT]];
	NSLog(@"Current date and time with offset: %@", currentDateTimeWithOffset);
	
}
return 0;

}[/code]

Follow the output that I got when I ran the program:

2012-05-13 08:17:42.579 Calendar[3414:403] Current date and time 1: 2012-05-13 11:17:42 +0000 2012-05-13 08:17:42.580 Calendar[3414:403] Current date and time 2: 2012-05-13 11:17:42 +0000 2012-05-13 08:17:42.581 Calendar[3414:403] Current date and time with offset: 2012-05-13 08:17:42 +0000