Reputation: 39
I had search on google how to get GMT Time in Objective-C, and I got this :
+ (NSString *)GetGMTTime{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
return [dateFormatter stringFromDate:[NSDate date]];}
Is there any way to add or set GMT Time ? (GMT+5)
Upvotes: 0
Views: 1088
Reputation: 27448
If you create NSDate
instance then it will return date in UTC or GMT
format by default.
Now when you convert this date to string by any date formatter then returned string (date) will be in local timezone (i.e. device's time zone).
You can create custom timezone with it's name to get date in that timezone.
NSDate *date = [NSDate date]; //give current date in UTC or GMT
NSLog(@"current date in gmt : %@",date);
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateInStrFormat = [df stringFromDate:date]; // this date(string format) will be in current timezone that was set in your device and
NSLog(@"current date in local or device's default timezone : %@",dateInStrFormat);
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Kolkata"];
NSLog(@"timezone : %@",timeZone);
[df setTimeZone:timeZone];
NSString *dateInCustomTimeZone = [df stringFromDate:date]; // this will return date in Asia/Kolkata's timezone
NSLog(@"date in custom timezone : %@",dateInCustomTimeZone);
NSLog(@"timezone : %@",timeZone);
will print something like, Asia/Kolkata (IST) offset 19800
. 19800
is offset, if you divide it with 3600
then you will get difference with gmt
like (+/- 5.30 etc)
Link for different timezone names
Or you can got timezone like,
NSTimeZone *timezone1 = [NSTimeZone timeZoneWithName:@"GMT+5:30"];
NSLog(@"timezone : %@",timezone1);
NSTimeZone *timeAone2 = [NSTimeZone timeZoneForSecondsFromGMT:60*60*5.5];
NSLog(@"timezone : %@",timeAone2);
Upvotes: 0
Reputation: 2459
The most flexible way is to use timeZoneForSecondsFromGMT
. This is more typo proof than using strings like GMT+X.
Here is a fuly working example:
+ (NSString *)GetGMTTime{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
NSTimeZone *gmt = [NSTimeZone timeZoneForSecondsFromGMT:(60*60*5)];
[dateFormatter setTimeZone:gmt];
return [dateFormatter stringFromDate:[NSDate date]];
}
It returns 2016-08-29T12:13 (when GMT time is 2016-08-29T7:13)
Note: 60*60*5
means 5 hours X 60 minutes X 60 seconds
Upvotes: 3
Reputation: 757
Can try like this.
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT+5:30"];
Upvotes: 2