IOS TimemZone根据当前的时区变化时间

本文探讨了在iOS平台上如何根据当前时区动态调整时间的方法,详细介绍了相关API的使用,帮助开发者实现应用程序中时间的精准显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  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];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值