计算某年某月份的最大天数,注意大小月,和闰年中的2月。
+ (NSInteger)dayMaxWithMonth:(NSInteger)month year:(NSInteger)year
{
NSInteger day = 30;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
day = 31;
}
else if (month == 4 || month == 6 || month == 9 || month == 11)
{
day = 30;
}
else if (month == 2)
{
day = 28;
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
{
day = 29; // 闰年
}
}
return day;
}
格式威治时间比北京时间慢8个小时,通过小时加上8个小时就是北京时间。
但需要注意,加上8个小时后的影响:
(1)判断小时数值是不是大于24了,是的话当前时间的天就要相应的加1;(2)判断天数值是不是大于当前年月对应的最大天数了,是的话当前的月要相应的加1;
(3)判断月数值是不是大于12了,是的话当前的年要相应的加1.
// 格林威治时间转北京时间(2018-01-24 07:13:23)
+ (NSString *)timeTextFromGMT:(NSString *)time
{
NSString *timeResult = time;
if (time && 0 < time.length)
{
NSString *yearText = [timeResult substringWithRange:NSMakeRange(0, 4)];
NSString *monthText = [timeResult substringWithRange:NSMakeRange(5, 2)];
NSString *dayText = [timeResult substringWithRange:NSMakeRange(8, 2)];
NSString *minuteText = [timeResult substringWithRange:NSMakeRange(14, 2)];
NSString *secondText = [timeResult substringWithRange:NSMakeRange(17, 2)];
NSString *hourText = [timeResult substringWithRange:NSMakeRange(11, 2)];
NSInteger hour = hourText.integerValue + 8;
if (hour >= 24)
{
hour = hour - 24;
// 日加1
NSInteger day = dayText.integerValue + 1;
NSInteger dayMax = [self dayMaxWithMonth:monthText.integerValue year:yearText.integerValue];
if (day > dayMax)
{
day = 1;
// 月加1
NSInteger month = monthText.integerValue + 1;
if (month > 12)
{
month = 1;
// 年加1
NSInteger year = yearText.integerValue + 1;
yearText = [NSString stringWithFormat:@"%@", @(year)];
}
monthText = [NSString stringWithFormat:@"%@%@", (month < 10 ? @"0" : @""), @(month)];
}
dayText = [NSString stringWithFormat:@"%@%@", (day < 10 ? @"0" : @""), @(day)];
}
hourText = [NSString stringWithFormat:@"%@%@", (hour < 10 ? @"0" : @""), @(hour)];
timeResult = [NSString stringWithFormat:@"%@-%@-%@ %@:%@:%@", yearText, monthText, dayText, hourText, minuteText, secondText];
}
return timeResult;
}