iOS開發(fā)丨NSDate的常用方法

NSDate是項目開發(fā)中常用的類,用于時間的轉換赫段,下面將一些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;
/// 將北京時區(qū)字符串轉換為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;
}

/// 將北京時區(qū)字符串轉換為手機當前utc時間
+ (long)beijingDateStringToUTC:(NSString *)dateString dateFormat:(NSString *)format {
    long utc = [self dateFormatToUTC:dateString dateFormat:format];
    NSInteger offset = [[NSTimeZone localTimeZone] secondsFromGMTForDate:[NSDate date]];  // 手機當前時區(qū)與格林威治時間的時間差
    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
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末看杭,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子挟伙,更是在濱河造成了極大的恐慌楼雹,老刑警劉巖模孩,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現場離奇詭異贮缅,居然都是意外死亡榨咐,警方通過查閱死者的電腦和手機,發(fā)現死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門谴供,熙熙樓的掌柜王于貴愁眉苦臉地迎上來块茁,“玉大人,你說我怎么就攤上這事桂肌∈福” “怎么了?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵崎场,是天一觀的道長佩耳。 經常有香客問我,道長谭跨,這世上最難降的妖魔是什么干厚? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮螃宙,結果婚禮上蛮瞄,老公的妹妹穿的比我還像新娘。我一直安慰自己谆扎,他們只是感情好挂捅,可當我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著燕酷,像睡著了一般籍凝。 火紅的嫁衣襯著肌膚如雪周瞎。 梳的紋絲不亂的頭發(fā)上苗缩,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天,我揣著相機與錄音声诸,去河邊找鬼酱讶。 笑死,一個胖子當著我的面吹牛彼乌,可吹牛的內容都是我干的泻肯。 我是一名探鬼主播,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼慰照,長吁一口氣:“原來是場噩夢啊……” “哼灶挟!你這毒婦竟也來了?” 一聲冷哼從身側響起毒租,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤稚铣,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體惕医,經...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡耕漱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了抬伺。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片螟够。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖峡钓,靈堂內的尸體忽然破棺而出妓笙,到底是詐尸還是另有隱情,我是刑警寧澤椒楣,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布给郊,位于F島的核電站,受9級特大地震影響捧灰,放射性物質發(fā)生泄漏淆九。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一毛俏、第九天 我趴在偏房一處隱蔽的房頂上張望炭庙。 院中可真熱鬧,春花似錦煌寇、人聲如沸络断。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽玄括。三九已至,卻和暖如春银锻,著一層夾襖步出監(jiān)牢的瞬間永品,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工击纬, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留鼎姐,地道東北人。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓更振,卻偏偏與公主長得像炕桨,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子肯腕,可洞房花燭夜當晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內容

  • 哎呦…… 我不想献宫,不想不想說話! 又是一整天沒出門实撒,昨天也是姊途,都是夜幕降臨時才帶著孩子出門去走一圈帖池,多...
    hxk古月閱讀 111評論 0 0
  • 今天凌晨五點多寂殉,我哥早早等我囚巴,因為今天我要回去了!回家去了友扰! 在送我回地鐵的路上彤叉,他叨叨絮絮說了很多!他說“有些事...
    木子吹瘋閱讀 178評論 0 0
  • 人生長恨水長東村怪,鴛鴦蝴蝶自成宗秽浇。 著作等身三千萬,婦孺皆知民國紅甚负。 小說第一快寫手柬焕,一支禿筆養(yǎng)家用。 伏案疾書月竹...
    顧勇詩書閱讀 479評論 0 5
  • 我總是拿自己的想象力消遣 路邊擺地攤的老者 亦或是立在欄桿上的少年 甚至是工程車上滾落的石塊 都跳進我的腦海中 成...
    扁竹桃仙人閱讀 202評論 2 4