7

Can someone help me to extract int timestamp value from this string "/Date(1242597600000)/" in Objective C

I would like to get 1242597600000.

Thx

3 Answers 3

15

One simple method:

NSString *timestampString = @"\/Date(1242597600000)\/";
NSArray *components = [timestampString componentsSeparatedByString:@"("];
NSString *afterOpenBracket = [components objectAtIndex:1];
components = [afterOpenBracket componentsSeparatedByString:@")"];
NSString *numberString = [components objectAtIndex:0];
long timeStamp = [numberString longValue];

Alternatively if you know the string will always be the same length and format, you could use:

NSString *numberString = [timestampString substringWithRange:NSMakeRange(7,13)];

And another method:

NSRange openBracket = [timestampString rangeOfString:@"("];
NSRange closeBracket = [timestampString rangeOfString:@")"];
NSRange numberRange = NSMakeRange(openBracket.location + 1, closeBracket.location - openBracket.location - 1);
NSString *numberString = [timestampString substringWithRange:numberRange];
Sign up to request clarification or add additional context in comments.

1 Comment

Edited to change NSRangeMake to NSMakeRange.
14

There's more than one way to do it. Here's a suggestion using an NSScanner;

NSString *dateString = @"\/Date(1242597600000)\/";
NSScanner *dateScanner = [NSScanner scannerWithString:dateString];
NSInteger timestamp;

if (!([dateScanner scanInteger:&timestamp])) {
    // scanInteger returns NO if the extraction is unsuccessful
    NSLog(@"Unable to extract string");
}

// If no error, then timestamp now contains the extracted numbers.

2 Comments

IMO NSScanner is the way to do it. I'm an NSScanner junkie =)
This does not extract the number. It fails because of the \/Date( prefix.
4
NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString* digitString = [timestampString stringByTrimmingCharactersInSet:nonDigits];
return [digitString longValue];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.