iOS NSDate相關

-(NSArray*) getDayTimeByNum:(NSInteger)num timeInterval:(NSInteger)interval
{
    NSMutableArray *hoursArr = [NSMutableArray array];
    NSDate *date;
    NSString *currentDateStr;
    
    for (int i=0; i<num; i++) {
        date = [[NSDate date] dateByAddingTimeInterval:(-interval*60*60*i)];
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd日HH時"];
        currentDateStr = [dateFormatter stringFromDate:date];
        
        [hoursArr addObject:currentDateStr];
    }
    
    // 倒序排列
    NSMutableArray *tempArr = [NSMutableArray array];
    for (int i = (int)[hoursArr count]; i>0; i--) {
        [tempArr addObject:[hoursArr objectAtIndex:i-1]];
    }
    hoursArr = tempArr;
    
    return hoursArr;
}

-(NSArray*) getWeekTimeByNum:(NSInteger)num timeInterval:(NSInteger)interval
{
    NSMutableArray *daysArr = [NSMutableArray array];
    NSDate *date;
    NSString *currentDateStr;
    
    for (int i=0; i<num; i++) {
        date = [[NSDate date] dateByAddingTimeInterval:(-interval*24*60*60*i)];
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM月dd日"];
        currentDateStr = [dateFormatter stringFromDate:date];
        
        [daysArr addObject:currentDateStr];
    }
    
    // 倒序排列
    NSMutableArray *tempArr = [NSMutableArray array];
    for (int i = (int)[daysArr count]; i>0; i--) {
        [tempArr addObject:[daysArr objectAtIndex:i-1]];
    }
    daysArr = tempArr;
    
    return daysArr;
}

-(NSDate*) getCurrentDate
{
    // 獲得時間對象
    NSDate *date = [NSDate date];
    // 獲得系統時區
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    // 以秒爲單位返回當前時間與系統格林尼治時間的差
    NSTimeInterval timeInterval = [timeZone secondsFromGMTForDate:date];
    // 然後把差的時間加上,就是當前系統準確的時間
    NSDate *currentDate = [date dateByAddingTimeInterval:timeInterval];
    NSLog(@"當前時間%@",currentDate);
    
    return currentDate;
}
<pre name="code" class="objc">// NSString->NSDate
-(NSString*) NSStringTurnToNSDate:(NSString*)dateStr dateFormat:(NSString*)format strFormat:(NSString*)strFormat
{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format]; // @"yyyy-MM-dd HH:mm:ss"
    
    NSDate *date= [dateFormatter dateFromString:dateStr];
    
    // 獲得系統時區
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    // 以秒爲單位返回當前時間與系統格林尼治時間的差
    NSTimeInterval timeInterval = [timeZone secondsFromGMTForDate:date];
    NSDate *dateTemp = [date dateByAddingTimeInterval:timeInterval];
    
    [dateFormatter setDateFormat:strFormat];
    NSString *str = [dateFormatter stringFromDate:dateTemp];
    
    return str;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章