日期中按年,月,日,分,时,星期,昨天,今天显示
@interface NSDate (PDate)
+(NSString *)stringWithTimeInterval:(NSTimeInterval)time;
- (BOOL)isYesterDay;
- (BOOL)isToday;
- (NSString *)stringWithExcludeThisYear;
- (BOOL)isEqualToDateIgnorTime:(NSDate *)date;
@end
//
// NSDate+PDate.m
//
// Created by hairong chen on 15/8/7.
// Copyright (c) 2015年 All rights reserved.
//
#import "NSDate+PDate.h"
@implementation NSDate (PDate)
- (NSDateComponents *)componentsOfDay
{
return [[NSCalendarcurrentCalendar]components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitNanosecondfromDate:self];
}
- (BOOL)isEqualToDateIgnorTime:(NSDate *)date
{
NSDateComponents *components = [selfcomponentsOfDay];
NSDateComponents *componentd = [datecomponentsOfDay];
return (componentd.year == components.year && components.month == componentd.month && components.day == componentd.day);
}
- (NSString *)stringWithExcludeThisYear
{
BOOL isThisYear =NO;
NSDate *nowDate = [NSDatedate];
if ([nowDatecomponentsOfDay].year != [selfcomponentsOfDay].year) {
isThisYear =NO;
}else{
isThisYear =YES;
}
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
if (isThisYear) {
[formattersetDateFormat:@"MM月dd日"];
}else{
[formattersetDateFormat:@"yyyy年MM月dd日"];
}
return [formatterstringFromDate:self];
}
//判断是否是今天
- (BOOL)isToday
{
NSDate *date = [NSDatedate];
return [selfisEqualToDateIgnorTime:date];
}
//判断是否是昨天
- (BOOL)isYesterDay
{
NSTimeInterval time = [[NSDatedate]timeIntervalSince1970]-24*60*60;
NSDate *yesterDayDate = [NSDatedateWithTimeIntervalSince1970:time];
return [selfisEqualToDateIgnorTime:yesterDayDate];
}
+(NSString *)stringWithTimeInterval:(NSTimeInterval)time
{
NSDate *date = [NSDatedateWithTimeIntervalSince1970:time];
NSInteger hour = [datecomponentsOfDay].hour;
NSInteger minute = [datecomponentsOfDay].minute;
NSTimeInterval nowTime = [[NSDatedate]timeIntervalSince1970];
if (nowTime - time>=7*24*60*60) {
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
[formattersetDateFormat:@"yyyy年MM月dd日 HH:mm"];
return [formatterstringFromDate:date];
}else{
if ([dateisToday]) {
return [NSStringstringWithFormat:@"今天 %ld:%ld",hour,minute];
}elseif ([dateisYesterDay]){
return [NSStringstringWithFormat:@"昨天 %ld:%ld",hour,minute];
}else{
NSArray *weekInfo =
@[@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六"];
NSInteger weekDay = [datecomponentsOfDay].weekday;
NSString *weekString = weekInfo[weekDay -1];
return [NSStringstringWithFormat:@"%@ %ld:%ld",weekString, hour,minute];
}
}
}
@end
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/baitxaps/article/details/47345607