TechnoGeezer
TechnoGeezer

Reputation: 197

How to convert timestamp to nsdate

I have a timestamp as below. Its in a string format "/Date(1402987019190+0000)/" I would like to convert it into NSDate. Can somebody help me into this one?

Upvotes: 0

Views: 1027

Answers (2)

Alexander Tkachenko
Alexander Tkachenko

Reputation: 3281

If I correctly understood what you mean, you need to parse timestamp from the string with given format. You can use regular expression to extract timestamp value.

NSString * timestampString = @"/Date(1402987019190+0000)/";
NSString *pattern = @"/Date\\(([0-9]{1,})\\+0000\\)/";

NSRegularExpression *regex = [NSRegularExpression
 regularExpressionWithPattern:pattern
                      options:NSRegularExpressionCaseInsensitive
                        error:nil];
NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:timestampString options:0 range:NSMakeRange(0, timestampString.length)];
NSRange matchRange = [textCheckingResult rangeAtIndex:1];
NSString *match = [timestampString substringWithRange:matchRange];

NSDate *date = [NSDate dateWithTimeIntervalSince1970:[match intValue];
NSLog(@"%@", date);

Upvotes: 1

Subodh Ghulaxe
Subodh Ghulaxe

Reputation: 18671

Use dateWithTimeIntervalSince1970:,

NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
NSLog(@"%@", date);

Use this function to convert string to timestamp Ref. https://stackoverflow.com/a/932130/1868660

-(NSString *)dateDiff:(NSString *)origDate {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setFormatterBehavior:NSDateFormatterBehavior10_4];
    [df setDateFormat:@"EEE, dd MMM yy HH:mm:ss VVVV"];
    NSDate *convertedDate = [df dateFromString:origDate];
    [df release];
    NSDate *todayDate = [NSDate date];
    double ti = [convertedDate timeIntervalSinceDate:todayDate];
    ti = ti * -1;
    if(ti < 1) {
        return @"never";
    } else  if (ti < 60) {
        return @"less than a minute ago";
    } else if (ti < 3600) {
        int diff = round(ti / 60);
        return [NSString stringWithFormat:@"%d minutes ago", diff];
    } else if (ti < 86400) {
        int diff = round(ti / 60 / 60);
        return[NSString stringWithFormat:@"%d hours ago", diff];
    } else if (ti < 2629743) {
        int diff = round(ti / 60 / 60 / 24);
        return[NSString stringWithFormat:@"%d days ago", diff];
    } else {
        return @"never";
    }   
}

Upvotes: 1

Related Questions