//
// Common.h
// TesTimeZone
//
// Created by li on 2018/1/13.
// Copyright © 2018年 li. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Common : NSObject
+ (NSString *)dateToString:(NSDate *)date;
+ (NSDate *)stringToDate:(NSString *)strdate;
+ (NSString *)getNowDateFromatAnDate:(NSDate *)anyDate;
@end
//
// Common.m
// TesTimeZone
//
// Created by li on 2018/1/13.
// Copyright © 2018年 li. All rights reserved.
//
#import "Common.h"
@implementation Common
+ (NSString *)dateToString:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:date];
// [dateFormatter release];
return strDate;
}
+ (NSDate *)stringToDate:(NSString *)strdate
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *retdate = [dateFormatter dateFromString:strdate];
// [dateFormatter release];
return retdate;
}
+ (NSString *)getNowDateFromatAnDate:(NSDate *)anyDate
{
//设置源日期时区
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT+0900"];//或GMT
//
NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
//设置转换后的目标日期时区
NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
//得到源日期与世界标准时间的偏移量
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
//目标日期与本地时区的偏移量
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
//得到时间偏移量的差值
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//转为现在时间
NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
NSString * dateStr = [Common dateToString:destinationDateNow];
return dateStr;
}
@end
调用:——–>
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UILabel * lable = [[UILabel alloc]init];
///////////////////////////////////////////
// NSString * currentDate = [Common dateToString:[NSDate date]];
NSString * testDateStr = @"2018-01-15 22:15:00";
NSString * currentDate = [Common getNowDateFromatAnDate:[Common stringToDate:testDateStr]];
////////////////////////////////////////////
lable.text = currentDate;
[lable sizeToFit];
lable.center = self.view.center;
[self.view addSubview:lable];
}