iOS 日期和时间问题.md

2021-03-31  本文已影响0人  儒徒

一、涉及的类: NSDate、NSDateFormatter、NSCalendar

二、获取今日的格式化日期

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *todayDate = [dateFormatter stringFromDate:[NSDate date]];
return todayDate;

yyyyMMdd:日期格式化

三、获取今日是周几

NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone localTimeZone];
NSDateComponents *comp = [calendar components:NSCalendarUnitWeekday
                                     fromDate:[NSDate date]];
NSInteger weekday =  [comp weekday];
if (weekday == 1) {//1: 星期天
    return @"7";
}else{
    /// 2:星期一, 3:星期二,... 7:星期六
    return weekday-1;
}

四、世界时间转换为本地时间

- (NSDate *)convertToLocalDateByWorldDate:(NSDate *)worldDate
{
    //当地时区
    NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
    //世界时间与当地时区的时间偏差值
    NSInteger offset = [localTimeZone secondsFromGMTForDate:worldDate];
    //世界时间+偏差值 计算得出
    NSDate *localDate = [worldDate dateByAddingTimeInterval:offset];
    return localDate;
}

五、将时间(毫秒)转化为“时分秒”

@property (nonatomic, assign) int currentHour;
@property (nonatomic, assign) int currentMinute;
@property (nonatomic, assign) int currentSecond;
@property (nonatomic, assign) int currentMillSecond;

///将时间(毫秒为单位)转化为“时分秒”形式. 
///比如: 后端返回了一个用户需倒计时时间完成的任务, 这个倒计时时间是多少呢
self.currentHour = totalTime/(60*60*1000);
int restTime = totalTime%(60*60*1000);
if (restTime>0) {
    self.currentMinute = restTime/(60*1000);
    restTime = restTime%(60*1000);
}else{
    self.currentMinute = 0;
}

if (restTime>0) {
    self.currentSecond = restTime/1000;
    restTime = restTime%1000;
}else{
    self.currentSecond = 0;
}

if (restTime>0) {
    self.currentMillSecond = restTime/100;
}else{
    self.currentMillSecond = 0;
}

六、日期格式化

yyyy:MM:dd HH:mm:ss
MM和mm的区别:MM表示月份,mm表示分钟
dd和DD的区别:dd表示当月的日期,DD表示从该年的1月1号到现在的天数
HH和hh的区别: HH表示24小时制格式, hh表示12小时制格式化

yyyy和YYYY的区别: YYYY是以周计算, yyyy:正常计算

如果一月1日是星期一,星期二,星期三,星期四,它是新的一年的第一周。
如果一月1日是星期五,星期六或星期日,它是前一年的52周或53周。

比如: 2019-12-29: 如果是yyyy格式化的日期是2019-12-29, 如果是YYYY格式化的日期是2020-12-29. image.png
上一篇 下一篇

猜你喜欢

热点阅读