views:

2301

answers:

3

Hi Guys,

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

I would like to get 1242597600000.

Thx

+2  A: 

One simple method:

NSArray *components = [timestampString componentsSeperatedByString:@"("];
NSString *afterOpenBracket = [components objectAtIndex:1];
components = [afterOpenBracket componentsSeperatedByString:@")"];
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 = NSRangeMake(openBracket.location + 1, closeBracket.location - openBracket.location - 1);
NSString *numberString = [timestampString substringWithRange:numberRange];
Tom
Thx, that helped me a lot
Mladen
+4  A: 

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])) {
    // scanInt return NO if it can't extract
    NSLog(@"Unable to extract string");
}

// If no error, then timestamp now contains the extracted numbers.
Abizern
IMO NSScanner is _the_ way to do it. I'm an NSScanner junkie =)
monowerker
+1  A: 
NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString* digitString = [timestampString stringByTrimmingCharactersInSet:nonDigits];
return [digitString longValue];
Nikolai Ruhe