Skip to content

Instantly share code, notes, and snippets.

@evgeniyd
Created September 27, 2016 12:19
Show Gist options
  • Save evgeniyd/58675a360dcc90d2d44a44fdf95425d8 to your computer and use it in GitHub Desktop.
Save evgeniyd/58675a360dcc90d2d44a44fdf95425d8 to your computer and use it in GitHub Desktop.
NSTimeZone extension to convert GMT offset strings to NSTimeZone objects. It handles uneven (half-an-hour) offsets, like "-4.5", "+3.5", etc.. NOTE: there are no test and testing for offsets like 45 minutes and similar.
#import <Foundation/Foundation.h>
@interface NSTimeZone (SBTExtensions)
/*!
@brief Convert seconds, represented as a string to the timezone. Returns nil when conversion failed.
The method covers both, integers and floating point numbers.
*/
+ (nullable instancetype)timeZoneForSecondsFromGMTString:(nonnull NSString *)secondsString;
@end
#import "NSTimeZone+SBTExtensions.h"
@implementation NSTimeZone (SBTExtensions)
+ (NSTimeZone *)timeZoneForSecondsFromGMTString:(NSString *)secondsString {
NSInteger secondsFromGMT = [secondsString floatValue] * 3600;
NSTimeZone* timeZone = [NSTimeZone timeZoneForSecondsFromGMT:secondsFromGMT];
return timeZone;
}
@end
#import <XCTest/XCTest.h>
#import "NSTimeZone+SBTExtensions.h"
@interface NSTimeZone_SBTExtensionsTests : XCTestCase
@end
@implementation NSTimeZone_SBTExtensionsTests
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testTimeZoneForSecondsFromGMTString {
NSString* inputString = @"+4.5";
NSTimeZone* testTimeZone = [NSTimeZone timeZoneForSecondsFromGMTString:inputString];
NSInteger seconds = testTimeZone.secondsFromGMT;
XCTAssertNotNil(testTimeZone);
XCTAssertTrue(seconds == 16200);
inputString = @"+4";
testTimeZone = [NSTimeZone timeZoneForSecondsFromGMTString:inputString];
seconds = testTimeZone.secondsFromGMT;
XCTAssertNotNil(testTimeZone);
XCTAssertTrue(seconds == 14400);
inputString = @"-12";
testTimeZone = [NSTimeZone timeZoneForSecondsFromGMTString:inputString];
seconds = testTimeZone.secondsFromGMT;
XCTAssertNotNil(testTimeZone);
XCTAssertTrue(seconds == -43200);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment