我想查看日期并以4格式TheDayBeforeY yesterday,Yesterady,Today,Tomorrow得到结果。
我有一个日期,我想将该日期与当前日期进行比较。
现在我已经这样做了,但这只是给我正数的日子,所以我不能让日期消失,或者它仍然会到那个日期。
-(void)getDateDiffrenceForBirthday:(NSString *)strOriginalDate
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *originalDate = [formatter dateFromString:strOriginalDate];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit
fromDate:originalDate
toDate:[NSDate date]
options:0];
NSLog(@"Days To Go %d",components.day);
}
答案 0 :(得分:2)
您可以使用此功能。它将参数日期格式化如下:
如果日期是明天,今天,昨天,前天,则返回相应的文本
如果日期少于一周前,则返回星期几,日和月
以中等格式格式化的所有其他日期
NSString* dateFormatted(NSDate* datetime){
if(datetime==nil){return nil;}
NSDate *todayWithTime=[NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents=[gregorian components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: todayWithTime];
NSDate *tomorrow=[[NSDate alloc] initWithTimeInterval:86399 sinceDate:[gregorian dateFromComponents: todayComponents]];
NSDateComponents * interval = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:datetime toDate:tomorrow options:0];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:CurrentLocale()];
NSString *result;
if((interval.year==0)&&(interval.month==0)){
if(interval.day==-1){
result=NSLocalizedString(@"Tomorrow", @"");
}else if(interval.day==0){
result=NSLocalizedString(@"Today", @"");
}else if(interval.day==1){
result=NSLocalizedString(@"Yesterday", @"");
}else if(interval.day==2){
result=NSLocalizedString(@"The Day Before Yesterday", @"");
}else if(interval.day<7){
[dateFormatter setDateFormat:@"EEEE, d MMMM"];
result = [dateFormatter stringFromDate:datetime];
}else{
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
result = [dateFormatter stringFromDate:datetime];
}
}else{
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
result = [dateFormatter stringFromDate:datetime];
}
return result;
}
答案 1 :(得分:1)
您可以尝试以下代码来获取日期差异
-(void)getDateDiffrenceForBirthday:(NSString *)strOriginalDate
{
NSDate *originalDate = [formatter dateFromString:strOriginalDate];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:originalDate toDate:[NSDate date] options:0];
NSLog(@"Days To Go %d",[components day]+1);
}