To Know Past & Future Like(Today,Yesterday, Tomorrow, one month ago, One month later etc)...
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
- (NSString *)relativeDateStringForDate:(NSDate *)date;
@end
#import "ViewController.h"
@interface ViewController ()
{
__weak IBOutlet UILabel *lblValue;
__weak IBOutlet UIDatePicker *datePicker;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// NSString *dateString = @"2016-04-27T18:30:00Z";
//
// NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
// NSDate *theDate = [formatter dateFromString:dateString];
// NSLog(@"The Date: %@", theDate);
}
- (IBAction)btnClicked:(id)sender
{
lblValue.text = [self relativeDateStringForDate:datePicker.date];
}
- (NSString *)relativeDateStringForDate:(NSDate *)date
{
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfYear |
NSCalendarUnitMonth | NSCalendarUnitYear;
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components1 = [cal components:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekOfYear) fromDate:[NSDate date]];
NSDate *today = [cal dateFromComponents:components1];
components1 = [cal components:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:date];
NSDate *thatdate = [cal dateFromComponents:components1];
// if `date` is before "now" (i.e. in the past) then the components will be positive
NSDateComponents *components = [[NSCalendar currentCalendar] components:units
fromDate:thatdate
toDate:today
options:0];
if ( labs(components.year) > 0) {
// year is most significant component
if (components.year > 0) {
// in the past
return [NSString stringWithFormat:@"%ld years ago", (long)components.year];
} else {
// in the future
return [NSString stringWithFormat:@"In %ld years", labs(components.year)];
}
}
else if (labs(components.month) > 0)
{
if (components.month > 0) {
// in the past
return [NSString stringWithFormat:@"%ld months ago", (long)components.month];
} else {
// in the future
return [NSString stringWithFormat:@"In %ld months", labs(components.month)];
}
}
else if (labs(components.weekOfYear) > 0)
{
if (components.weekOfYear > 0) {
// in the past
return [NSString stringWithFormat:@"%ld weeks ago", (long)components.weekOfYear];
} else {
// in the future
return [NSString stringWithFormat:@"In %ld weeks", labs(components.weekOfYear)];
}
}
else if (labs(components.day) > 0)
{
if (components.day > 0) {
if (components.day > 1)
{
return [NSString stringWithFormat:@"%ld days ago", (long)components.day];
}
else
{
return @"Yesterday";
}
} else {
if (components.day < -1)
{
return [NSString stringWithFormat:@"In %ld days ", labs(components.day)];
}
else
{
return @"Tomorrow";
}
}
}
else {
return @"Today";
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
No comments:
Post a Comment