美文网首页程序开发
iOS开发丨NSDate的常用方法

iOS开发丨NSDate的常用方法

作者: 炼心术师 | 来源:发表于2020-01-11 14:26 被阅读0次

    NSDate是项目开发中常用的类,用于时间的转换,下面将一些NSDate常用的方法集成在一个类DateConversion中,以供调用。

    DateConversion.h文件如下:

    #import <Foundation/Foundation.h>
    
    @interface DateConversion : NSObject
    
    /// 获取默认的date formatter
    + (NSDateFormatter *)getDateFormatter;
    /// 将utc时间转换为默认日期格式字符串
    + (NSString *)utcToDateString:(long)utc;
    /// 将utc时间转换为字符串, @"yyyy MM dd HH:mm:ss Z", 英文模式 MMM
    + (NSString *)utcToDateString:(long)utc dateFormat:(NSString *)format;
    /// 将字符串转换为utc时间
    + (long)dateFormatToUTC:(NSString *)dateString dateFormat:(NSString *)format;
    /// 将北京时区字符串转换为utc时间
    + (long)beijingDateStringToUTC:(NSString *)dateString dateFormat:(NSString *)format;
    /// 将时间转换为新的格式
    + (NSString *)dateStringToFormatString:(NSString *)dateStr format:(NSString *)format toFormat:(NSString *)toFormat;
    /// 获取每周第一天的utc
    + (long)getFirstUTCInWeekForUTC:(long)utc;
    /// 获取每周最后一天的utc
    + (long)getLastUTCInWeekForUTC:(long)utc;
    /// 获取当前utc是在以周日开始的一周的第几天
    + (int)getWeekDayForUTC:(long)utc;
    /// 获取每月第一天的utc
    + (long)getFistDayUTCInMonthForUTC:(long)utc;
    /// 获取每年第一天的utc
    + (long)getFistDayUTCInYearForUTC:(long)utc;
    /// 获取本月天数
    + (int)getDaysInThisMonthWithUTC:(long)utc;
    /// 获取本年天数
    + (int)getDaysInThisYearWithUTC:(long)utc;
    /// 计算 utc 时间为周几
    + (NSString *)getWeekStringForUTC:(long)utc;
    /// 获取月份文本
    + (NSString *)getMonthString:(NSInteger)index;
    /// 获取随机整数值
    + (int)getRandomInt:(int)from to:(int)to;
    /// 获取随机浮点数值
    + (float)getRandomFloat:(float)from to:(float)to;
    /// 获取时间文本 xHxxMin
    + (NSString *)getTimeString:(int)time;
    //// 获取时间文本 HH:MM
    + (NSString *)getHourMinuTimeString:(int)time;
    /// 获取日期文本,是否显示年
    + (NSString *)dateStringWithUTC:(long)utc year:(BOOL)year;
    
    @end
    

    DateConversion.m文件如下:

    #import "DateConversion.h"
    
    @implementation DateConversion
    
    /// 获取默认的date formatter
    + (NSDateFormatter *)getDateFormatter {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]];  // 获得正确的返回日期,避免日本日历、佛教日历取date异常
        [dateFormatter setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]];
        return dateFormatter;
    }
    
    /// 将utc时间转换为默认日期格式字符串
    + (NSString *)utcToDateString:(long)utc {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateStyle = NSDateFormatterMediumStyle;
        dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]];  // 获得正确的返回日期,避免日本日历、佛教日历取date异常
        [dateFormatter setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]];
        NSString *dateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:utc]];
        return dateString;
    }
    
    /// 将utc时间转换为字符串, @"yyyy MM dd HH:mm:ss Z", 英文模式 MMM
    + (NSString *)utcToDateString:(long)utc dateFormat:(NSString *)format {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = format;
        dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]];  // 获得正确的返回日期,避免日本日历、佛教日历取date异常
        [dateFormatter setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]];
        NSString *dateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:utc]];
        return dateString;
    }
    
    /// 将字符串转换为utc时间
    + (long)dateFormatToUTC:(NSString *)dateString dateFormat:(NSString *)format {
        long utc = 0;
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = format;
        dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]];  // 获得正确的返回日期,避免日本日历、佛教日历取date异常
        [dateFormatter setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]];
        utc = [[dateFormatter dateFromString:dateString] timeIntervalSince1970];
        return utc;
    }
    
    /// 将北京时区字符串转换为手机当前utc时间
    + (long)beijingDateStringToUTC:(NSString *)dateString dateFormat:(NSString *)format {
        long utc = [self dateFormatToUTC:dateString dateFormat:format];
        NSInteger offset = [[NSTimeZone localTimeZone] secondsFromGMTForDate:[NSDate date]];  // 手机当前时区与格林威治时间的时间差
        utc = utc + offset - 8*3600;
        return utc;
    }
    
    /// 将时间转换为新的格式
    + (NSString *)dateStringToFormatString:(NSString *)dateStr format:(NSString *)format toFormat:(NSString *)toFormat {
        NSDateFormatter *curFormat = [[NSDateFormatter alloc] init];
        curFormat.dateFormat = format;
        // 获得正确的返回日期,避免日本日历、佛教日历取date异常的问题
        NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]];
        [curFormat setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]];
        [curFormat setLocale:locale];
        
        NSDateFormatter *newFormat = [[NSDateFormatter alloc] init];
        newFormat.dateFormat = toFormat;
        [newFormat setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]];
        [newFormat setLocale:locale];
        
        NSString *formatString = [newFormat stringFromDate:[curFormat dateFromString:dateStr]];
        return formatString;
    }
    
    /// 获取每周第一天的utc
    + (long)getFirstUTCInWeekForUTC:(long)utc {
        NSDateComponents *comp = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] components:NSCalendarUnitYear|NSCalendarUnitMonth|kCFCalendarUnitDay|kCFCalendarUnitWeekday
                                                                 fromDate:[NSDate dateWithTimeIntervalSince1970:utc]];
        comp.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
        /// 1(星期天) 2(星期一) 3(星期二) 4(星期三) 5(星期四) 6(星期五) 7(星期六)
        int week[7] = {1, 2, 3, 4, 5, 6, 7};
        int current_wd = week[[comp weekday] - 1];  /// 当前星期
        long first_utc = utc - (current_wd - 1) * 24 * 3600;
        return first_utc;
    }
    
    /// 获取每周最后一天的utc
    + (long)getLastUTCInWeekForUTC:(long)utc {
        NSDateComponents *comp = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] components:NSCalendarUnitYear|NSCalendarUnitMonth|kCFCalendarUnitDay|kCFCalendarUnitWeekday
                                                                 fromDate:[NSDate dateWithTimeIntervalSince1970:utc]];
        comp.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
        /// 1(星期天) 2(星期一) 3(星期二) 4(星期三) 5(星期四) 6(星期五) 7(星期六)
        int week[7] = {1, 2, 3, 4, 5, 6, 7};
        int current_wd = week[[comp weekday] - 1];  /// 当前星期
        long last_utc = utc - (current_wd - 7) * 24 * 3600;
        return last_utc;
    }
    
    /// 获取当前utc是在以周日开始的一周的第几天
    + (int)getWeekDayForUTC:(long)utc {
        NSDateComponents *comp = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] components:NSCalendarUnitYear|NSCalendarUnitMonth|kCFCalendarUnitDay|kCFCalendarUnitWeekday
                                                                 fromDate:[NSDate dateWithTimeIntervalSince1970:utc]];
        comp.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
        return (int)[comp weekday];
    }
    
    /// 获取每月第一天的utc
    + (long)getFistDayUTCInMonthForUTC:(long)utc {
        NSString *year = [DateConversion utcToDateString:utc dateFormat:@"yyyy MM"];
        NSString *firstday = [NSString stringWithFormat:@"%@ 01", year];
        return [DateConversion dateFormatToUTC:firstday dateFormat:@"yyyy MM dd"];
    }
    
    /// 获取每年第一天的utc
    + (long)getFistDayUTCInYearForUTC:(long)utc {
        NSString *year = [DateConversion utcToDateString:utc dateFormat:@"yyyy"];
        NSString *firstday = [NSString stringWithFormat:@"%@ 01 01", year];
        return [DateConversion dateFormatToUTC:firstday dateFormat:@"yyyy MM dd"];
    }
    
    /// 获取本月天数
    + (int)getDaysInThisMonthWithUTC:(long)utc {
        NSRange daysInLastMonth = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] rangeOfUnit:NSCalendarUnitDay
                                                                     inUnit:NSCalendarUnitMonth
                                                                    forDate:[NSDate dateWithTimeIntervalSince1970:utc]];
        return (int)daysInLastMonth.length;
    }
    
    /// 获取本年天数
    + (int)getDaysInThisYearWithUTC:(long)utc {
        int year = [[self utcToDateString:utc dateFormat:@"yyyy"] intValue];
        int days = 365;
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            days = 366; /// 闰年366天
        }
        return days;
    }
    
    /// 计算 utc 时间为周几
    + (NSString *)getWeekStringForUTC:(long)utc {
        int day = [DateConversion getWeekDayForUTC:utc] - 1;
        NSArray *weekArr = @[NSLocalizedString(@"calendar_sun", nil),
                             NSLocalizedString(@"calendar_mon", nil),
                             NSLocalizedString(@"calendar_tue", nil),
                             NSLocalizedString(@"calendar_wed", nil),
                             NSLocalizedString(@"calendar_thu", nil),
                             NSLocalizedString(@"calendar_fri", nil),
                             NSLocalizedString(@"calendar_sat", nil),];
        return weekArr[day];
    }
    
    /// 获取月份文本
    + (NSString *)getMonthString:(NSInteger)index {
        NSArray *monthArr = @[NSLocalizedString(@"January", nil),
                              NSLocalizedString(@"February", nil),
                              NSLocalizedString(@"March", nil),
                              NSLocalizedString(@"April", nil),
                              NSLocalizedString(@"May", nil),
                              NSLocalizedString(@"June", nil),
                              NSLocalizedString(@"July", nil),
                              NSLocalizedString(@"August", nil),
                              NSLocalizedString(@"September", nil),
                              NSLocalizedString(@"October", nil),
                              NSLocalizedString(@"November", nil),
                              NSLocalizedString(@"December", nil)];
        return monthArr[index - 1];
    }
    
    /// 获取随机整数值
    + (int)getRandomInt:(int)from to:(int)to {
        return (int)(from + (arc4random() % (to - from + 1)));
    }
    
    /// 获取随机浮点数值
    + (float)getRandomFloat:(float)from to:(float)to {
        float diff = to - from;
        return (((float) arc4random() / UINT_MAX) * diff) + from;
    }
    
    //// 获取时间文本 xHxxMin
    + (NSString *)getTimeString:(int)time {
        int hour = time / 60;
        int minu = time - hour*60;
        if (hour != 0 && minu < 0) {
            minu = abs(minu);
        }
        NSString *str_1 = hour == 0 ? @"" : [NSString stringWithFormat:@"%d", hour];
        NSString *str_2 = hour == 0 ? @"" : [NSString stringWithFormat:@"%@", NSLocalizedString(@"sleep_hour", nil)];
        NSString *str_3 = [NSString stringWithFormat:@"%d", minu];
        NSString *str_4 = [NSString stringWithFormat:@"%@", NSLocalizedString(@"sleep_min", nil)];
        if (minu == 0) {
            str_3 = @"";
            str_4 = @"";
        }
        return [NSString stringWithFormat:@"%@%@%@%@", str_1, str_2, str_3, str_4];
    }
    
    //// 获取时间文本 HH:MM
    + (NSString *)getHourMinuTimeString:(int)time {
        if (time == 0) {
            return [NSString stringWithFormat:@"--:--"];
        }
        int hour = time / 60;
        int minu = time - hour*60;
        if (hour != 0 && minu < 0) {
            minu = abs(minu);
        }
        return [NSString stringWithFormat:@"%02d:%02d", hour, minu];
    }
    
    /// 获取日期文本,是否显示年
    + (NSString *)dateStringWithUTC:(long)utc year:(BOOL)year {
        NSDateComponents *comp = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] components:NSCalendarUnitYear|NSCalendarUnitMonth|kCFCalendarUnitDay|kCFCalendarUnitHour|kCFCalendarUnitMinute|kCFCalendarUnitSecond|kCFCalendarUnitWeekday
                                                                 fromDate:[NSDate dateWithTimeIntervalSince1970:utc]];
        comp.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
        NSString *dateString = @"";
        if ([APPModelManager isChinaCalendar]) {
            if (year) {
                dateString = [NSString stringWithFormat:@"%@%@%@",
                              [NSString stringWithFormat:@"%zi%@", comp.year, NSLocalizedString(@"report_year", nil)],
                              [NSString stringWithFormat:@"%zi%@", comp.month, NSLocalizedString(@"report_month", nil)],
                              [NSString stringWithFormat:@"%zi%@", comp.day, NSLocalizedString(@"report_day", nil)]];
            }
            else {
                dateString = [NSString stringWithFormat:@"%@%@",
                              [NSString stringWithFormat:@"%zi%@", comp.month, NSLocalizedString(@"report_month", nil)],
                              [NSString stringWithFormat:@"%zi%@", comp.day, NSLocalizedString(@"report_day", nil)]];
            }
        }
        else {
            if (year) {
                NSString *yeaStr = [NSString stringWithFormat:@"%zi", comp.year];
                NSString *monStr = [DateConversion getMonthString:comp.month];
                NSString *dayStr = [NSString stringWithFormat:@"%zi", comp.day];
                dateString = [NSString stringWithFormat:@"%@ %@, %@", monStr, dayStr, yeaStr];
            }
            else {
                NSString *monStr = [DateConversion getMonthString:comp.month];
                NSString *dayStr = [NSString stringWithFormat:@"%zi", comp.day];
                dateString = [NSString stringWithFormat:@"%@ %@", monStr, dayStr];
            }
        }
        return dateString;
    }
    
    @end
    

    相关文章

      网友评论

        本文标题:iOS开发丨NSDate的常用方法

        本文链接:https://www.haomeiwen.com/subject/vnovactx.html