How to parse strings in Objective-C

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

I want to get 1242597600000.

thanks

+5
source share
3 answers

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 that the string will always be the same length and format, you can use:

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

And one more way:

NSRange openBracket = [timestampString rangeOfString:@"("];
NSRange closeBracket = [timestampString rangeOfString:@")"];
NSRange numberRange = NSMakeRange(openBracket.location + 1, closeBracket.location - openBracket.location - 1);
NSString *numberString = [timestampString substringWithRange:numberRange];
+14
source

There is more than one way to do this. It is proposed to use 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.
+12
source
NSCharacterSet* nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSString* digitString = [timestampString stringByTrimmingCharactersInSet:nonDigits];
return [digitString longValue];
+3
source

All Articles