Some tips with timer in iOS

/
0 Comments
Have you ever face to change time with different timezone in iOS? Or something like this one


Basically, the solution is very simple by using this way: you change the local timezone to GMT time then whatever you want to use it, just revert again. I've just done NSDate+Helper to help you a little bit

.h file
@interface NSDate (Helper)
+ (NSDate *)convertSystemDateToGMTDate;
+ (NSDate *)convertGMTDateToSystemDateWithString:(float)interval;
+ (NSString *)stringWithDate:(NSDate *)date;
@end

.m file

@implementation NSDate (Helper)
+ (NSString *)timestampFormatString {
return @"yyyy-MM-dd'T'HH:mm:ss";}
+ (NSString *)dbFormatString {
return [NSDate timestampFormatString];}
+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format {
NSDateFormatter *inputFormatter = [NSDateFormatter new];[inputFormatter setDateFormat:format];
NSDate *date = [inputFormatter dateFromString:string];
return date;
}
+ (NSDate *)dateFromString:(NSString *)string {
return [NSDate dateFromString:string withFormat:[NSDate dbFormatString]];}
+ (NSDate *)convertSystemDateToGMTDate
{
    NSDate* sourceDate = [NSDate date];
    NSTimeZone* sourceTimeZone = [NSTimeZone systemTimeZone];
    NSTimeZone* destinationTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
  
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
  
    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
    return destinationDate;
}
+ (NSDate *)convertGMTDateToSystemDateWithString:(float)interval
{
    NSDate* sourceDate = [NSDate dateWithTimeIntervalSince1970:interval];
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
  
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interTime = destinationGMTOffset - sourceGMTOffset;
  
    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interTime sinceDate:sourceDate];
  
    return destinationDate;
}
+ (NSString *)stringWithDate:(NSDate *)date {
    NSString *result = @"";
    NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
    [displayFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
  
    result = [displayFormatter stringFromDate:date];
    return result;
}
@end 


You may also like

No comments:

Member of Mroom Software. Powered by Blogger.