31 Mar 2017

Date Picker & To find Today, YesterDay, Days ago, weeks ago,months ago,years ago from given Date...




Date Picker & To find Today, YesterDay, Days ago, weeks ago,months ago,years ago from given Date...




#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) 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 (components.year > 0)
    {
        return [NSString stringWithFormat:@"%ld years ago", (long)components.year];
    }
    else if (components.month > 0)
    {
        return [NSString stringWithFormat:@"%ld months ago", (long)components.month];
    }
    else if (components.weekOfYear > 0)
    {
        return [NSString stringWithFormat:@"%ld weeks ago", (long)components.weekOfYear];
    }
    else if (components.day > 0)
    {
        if (components.day > 1)
        {
            return  [NSString stringWithFormat:@"%ld days ago", (long)components.day];
        }
        else
        {
            return @"Yesterday";
        }
    }
    else
    {
        return @"Today";
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end

No comments:

Post a Comment

Recent Posts

Codable demo

Link: https://www.dropbox.com/s/kw7c1kgv1628bh7/codableDemo.zip?dl=0