-2

I have NSString that has value "22/04/2013 05:56", as per the requirement I just want to calculate this time and date and show some condition based messages.

First condition: If (String date = current date and stringtime = current time)||(string date = current date and string time < 1 minute from current time)

Second condition: If (String date = current date and stringtime > current time by how many minutes or hour)

Third Condition: To know is string date is yesterday.

Fourth Condition: To Know is string date is day before yesterday.

I am receiving this string from server. How can I achieve above things with this "22/04/2013 05:56" string.

iMash
  • 1,178
  • 1
  • 12
  • 33
  • First of all will you please let me know, who have downvote this question and why? – iMash Jul 25 '13 at 06:27
  • 2
    This forum is not for down vote any question without reading it carefully and understand it. If above question has some discrepancy you can correct it instead to down vote or else you can put your talent by resolving it. – iMash Jul 25 '13 at 06:53

2 Answers2

5

You need to take 2 step:

  1. convert string to NSDate
  2. convert date to timeStamp

like below:

- (void) dateConverter{
    NSString *string = @"22/04/2013 05:56";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // this is imporant - we set our input date format to match our input string
    // if format doesn't match you'll get nil from your string, so be careful
    [dateFormatter setDateFormat:@"dd/MM/yyyy hh:mm"];
    NSDate *date = [[NSDate alloc] init];
    // voila!
    date = [dateFormatter dateFromString:string];
    NSLog(@"dateFromString = %@", date);

    //date to timestamp
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
}

Then to achieve something like time ago following method will help, although it's not totally for you bu i believe you can modify it to help you!

- (NSString *) timeAgoFor : (NSDate *) date {
    double ti = [date timeIntervalSinceDate:[NSDate date]];
    ti = ti * -1;

    if (ti < 86400) {//86400 = seconds in one day
        return[NSString stringWithFormat:@"Today"];
    } else if (ti < 86400 * 2) {
        return[NSString stringWithFormat:@"Yesterday"];
    }else if (ti < 86400 * 7) {
        int diff = round(ti / 60 / 60 / 24);
        return[NSString stringWithFormat:@"%d days ago", diff];
    }else {
        int diff = round(ti / (86400 * 7));
        return[NSString stringWithFormat:@"%d wks ago", diff];
    }
}
rptwsthi
  • 10,094
  • 10
  • 68
  • 109
0

From string using dateformatter convert it to date.Then you have to compare the dates and get the value

NSString *str=@"22/04/2013 05:56";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd/MM/YYYY hh:mm"];
NSDate *dateObj= [dateFormatter dateFromString:str];
NSLog(@"%@",dateObj);
Lithu T.V
  • 19,955
  • 12
  • 56
  • 101