美文网首页
日期Date

日期Date

作者: 阿龍飛 | 来源:发表于2016-11-18 15:09 被阅读14次

    iOS-时间与日期详解http://www.jianshu.com/p/f8aab37a27ff
    https://github.com/MatthewYork/DateTools
    iOS日历、日期、时间的计算http://www.jianshu.com/p/692bb0a7269c
    iOS开发tips之日期与星期的对应http://www.jianshu.com/p/804d22fd5180
    判断NSDate是星期几和农历http://www.jianshu.com/p/5850a5d03b8f

    NSDate的8小时问题:初始化一个NSDate时间[NSDate date],获取的是零时区的时间(格林尼治的时间: 年-月-日 时:分:秒: +时区),而北京时间是东八区时间,因为时区不同,所以打印的时间相差了8小时。

    NSDate *date = [NSDate date];
    NSLog(@"date时间 = %@", date);
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
    NSString *dateStr = [formatter stringFromDate:date];
    NSLog(@"字符串时间 = %@", dateStr);
    
    2016-12-07 10:44:24.470 timeTest[32743:2995134] date时间 = 2016-12-07 02:44:24 +0000
    2016-12-07 10:44:24.471 timeTest[32743:2995134] 字符串时间 = 2016-12-07 10:44:24 +0800
    

    也可以设置时区,获取指定时区的字符串时间

    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];//东八区时间
    NSString *dateStr = [formatter stringFromDate:date];
    NSLog(@"字符串时间 = %@", dateStr);
    

    TimeToolsManger

    #import <Foundation/Foundation.h>
    
    #define DEFAULT_DATE_TEMPLATE_STRING @"yyyy-MM-dd HH:mm:ss"
    #define DEFAULT_SHORT_DATE_TEMPLATE_STRING @"yyyy-MM-dd HH:mm"
    #define SHORT_DATE_TEMPLATE_STRING @"yyyy-MM-dd"
    #define HOUR_MINUT_TEMPLATE_STRING @"HH:mm"
    #define DETAIL_DATE_TEMPLATE_STRING @"yyyy年MM月dd日"
    #define MONTH_DATE_TEMPLATE_STRING @"yyyy-MM"
    
    @interface TimeToolsManger : NSObject
    
    /**
     *  获取单例对象
     */
    + (instancetype)shareToolsManager;
    
    ///日期格式转字符串
    + (NSString *)dateToString:(NSDate *)date withDateFormat:(NSString *)format;
    
    ///字符串转日期格式
    + (NSDate *)stringToDate:(NSString *)dateString withDateFormat:(NSString *)format;
    
    ///根据时间取得今天是星期几
    + (NSString*)weekdayStringFromDate:(NSDate*)inputDate ;
    
    ///根据当前时间获取下一个月的今天
    +(NSString*)getNextMonth:(NSUInteger)number;
    
    ///根据当前时间获取上一个月的今天
    +(NSString*)getLastMonth:(NSUInteger)number;
    
    ///以秒为整数值 时间戳->字符串
    + (NSString *)timeWithTimeIntervalString:(NSString *)timeString;
    
    ///以秒为整数值 获取当前时间戳
    + (NSString *)dateTimeIntervalString;
    
    ///聊天界面通过时间戳得到标准格式的字符串
    +(NSString *)getMessageDateStringFromTimeInterval:(NSTimeInterval)TimeInterval andNeedTime:(BOOL)needTime;
    + (NSString*)getMessageDateString:(NSDate*)messageDate andNeedTime:(BOOL)needTime;
    +(NSString *)getWeekdayWithNumber:(NSInteger)number;
    
    ///计算距离当前时间天数
    +(NSString*)residueDays:(NSString*)dateString;
    
    ///计算距离未来时间天数
    +(NSString*)futureDays:(NSString*)dateString;
    @end
    
    //
    //  TimeToolsManger.m
    //  test123
    //
    //  Created by 29 on 16/12/13.
    //  Copyright © 2016年 aiitex. All rights reserved.
    //
    
    #import "TimeToolsManger.h"
    
    @implementation TimeToolsManger
    
    + (instancetype)shareToolsManager {
        static TimeToolsManger *manager = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            manager = [[TimeToolsManger alloc] init];
        });
        return manager;
    }
    
    ///根据时间取得今天是星期几
    
    + (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
        
        NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
        
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        
        NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
        
        [calendar setTimeZone: timeZone];
        
        NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
        
        NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
        
        return [weekdays objectAtIndex:theComponents.weekday];
        
    }
    
    ///根据当前时间获取下一个月的今天
    
    +(NSString*)getNextMonth:(NSUInteger)number{
        NSDate * mydate = [NSDate date];
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *comps = nil;
        comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:mydate];
        NSDateComponents *adcomps = [[NSDateComponents alloc] init];
        [adcomps setYear:0];
        [adcomps setMonth:number];
        [adcomps setDay:0];
        NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
        NSString *beforDate = [dateFormatter stringFromDate:newdate];
        return beforDate;
    }
    
    ///根据当前时间获取上一个月的今天
    
    +(NSString*)getLastMonth:(NSUInteger)number{
        NSDate * mydate = [NSDate date];
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *comps = nil;
        comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:mydate];
        NSDateComponents *adcomps = [[NSDateComponents alloc] init];
        [adcomps setYear:0];
        [adcomps setMonth:-number];
        [adcomps setDay:0];
        NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
        NSString *beforDate = [dateFormatter stringFromDate:newdate];
        return beforDate;
    }
    
    
    ///日期格式转字符串
    + (NSString *)dateToString:(NSDate *)date withDateFormat:(NSString *)format
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:format];
        NSString *strDate = [dateFormatter stringFromDate:date];
        return strDate;
    }
    
    ///字符串转日期格式
    + (NSDate *)stringToDate:(NSString *)dateString withDateFormat:(NSString *)format
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:format];
        
        NSDate *date = [dateFormatter dateFromString:dateString];
        
        ///将世界时间转化为中国区时间
        NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
        NSInteger interval = [timeZone secondsFromGMTForDate:date];
        NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
        
        return localeDate;
    }
    ///以秒为整数值的时间戳转换
    + (NSString *)timeWithTimeIntervalString:(NSString *)timeString
    {
        NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
        formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
    
        NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
        NSString* dateString = [formatter stringFromDate:date];
        return dateString;
    }
    
    ///以秒为整数值 获取当前时间戳
    + (NSString *)dateTimeIntervalString{
        NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[date timeIntervalSince1970]; // *1000 是精确到毫秒,不乘就是精确到秒
        NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //转为字符型
        return timeString;
    }
    
    ///聊天界面通过时间戳得到标准格式的字符串
    +(NSString *)getMessageDateStringFromTimeInterval:(NSTimeInterval)TimeInterval andNeedTime:(BOOL)needTime
    {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:TimeInterval];
        return [TimeToolsManger getMessageDateString:date andNeedTime:needTime];
    }
    
    + (NSString*)getMessageDateString:(NSDate*)messageDate andNeedTime:(BOOL)needTime
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setLocale:[NSLocale systemLocale]];
        [formatter setTimeZone:[NSTimeZone systemTimeZone]];
        [formatter setDateFormat:@"YYYY/MM/dd HH:mm"];
        
        NSCalendar *cal = [NSCalendar currentCalendar];
        NSDateComponents *components = [cal components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:messageDate];
        NSDate *msgDate = [cal dateFromComponents:components];
        
        NSString*weekday = [TimeToolsManger getWeekdayWithNumber:components.weekday];
        
        components = [cal components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:[NSDate date]];
        NSDate *today = [cal dateFromComponents:components];
        
        if([today isEqualToDate:msgDate]){
            if (needTime) {
                [formatter setDateFormat:@"今天 HH:mm"];
            }
            else{
                [formatter setDateFormat:@"今天"];
            }
            return [formatter stringFromDate:messageDate];
        }
        
        components.day -= 1;
        NSDate *yestoday = [cal dateFromComponents:components];
        if([yestoday isEqualToDate:msgDate]){
            if (needTime) {
                [formatter setDateFormat:@"昨天 HH:mm"];
            }
            else{
                [formatter setDateFormat:@"昨天"];
            }
            return [formatter stringFromDate:messageDate];
        }
        
        for (int i = 1; i <= 6; i++) {
            components.day -= 1;
            NSDate *nowdate = [cal dateFromComponents:components];
            if([nowdate isEqualToDate:msgDate]){
                if (needTime) {
                    [formatter setDateFormat:[NSString stringWithFormat:@"%@ HH:mm",weekday]];
                }
                else{
                    [formatter setDateFormat:[NSString stringWithFormat:@"%@",weekday]];
                }
                return [formatter stringFromDate:messageDate];
            }
        }
        
        while (1) {
            components.day -= 1;
            NSDate *nowdate = [cal dateFromComponents:components];
            if ([nowdate isEqualToDate:msgDate]) {
                if (!needTime) {
                    [formatter setDateFormat:@"YYYY/MM/dd"];
                }
                return [formatter stringFromDate:messageDate];
                break;
            }
        }
    }
    
    //1代表星期日、如此类推
    +(NSString *)getWeekdayWithNumber:(NSInteger)number
    {
        switch (number) {
            case 1:
                return @"星期日";
                break;
            case 2:
                return @"星期一";
                break;
            case 3:
                return @"星期二";
                break;
            case 4:
                return @"星期三";
                break;
            case 5:
                return @"星期四";
                break;
            case 6:
                return @"星期五";
                break;
            case 7:
                return @"星期六";
                break;
            default:
                return @"";
                break;
        }
    }
    
    ///计算距离当前时间天数
    +(NSString*)residueDays:(NSString*)dateString{
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate *date1 = [dateFormatter dateFromString:dateString];
        NSDate *date  = [dateFormatter dateFromString:[TimeToolsManger dateToString:[NSDate date] withDateFormat:@"yyyy-MM-dd"]];
        NSTimeInterval time = [date timeIntervalSinceDate:date1];
        int days = ((int)time)/(3600*24);
        NSString *dateContent = [[NSString alloc] initWithFormat:@"%i",days];
        return dateContent;
    }
    
    ///计算距离未来时间天数
    +(NSString*)futureDays:(NSString*)dateString{
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate *date1 = [dateFormatter dateFromString:dateString];
        NSDate *date  = [dateFormatter dateFromString:[TimeToolsManger dateToString:[NSDate date] withDateFormat:@"yyyy-MM-dd"]];
        NSTimeInterval time = [date1 timeIntervalSinceDate:date];
        int days = ((int)time)/(3600*24);
        NSString *dateContent = [[NSString alloc] initWithFormat:@"%i",days];
        return dateContent;
    }
    @end
    
    

    相关文章

      网友评论

          本文标题:日期Date

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