Jan49
Jan49

Reputation: 1818

Date.parse in ios?

Is there any method in ios which is similar to date.parse() in javascript?

    value = Date.parse(date.value + ' ' + time.value);// javascript

i need corresponding code for ios to get values from textfield and convert into date with different time format

Also it is automatically convert into local timezone in javascript, is there any correspondings in ios?

Upvotes: 0

Views: 323

Answers (3)

Rob
Rob

Reputation: 437432

Generally we'd advise you consider NSDateFormatter (see class reference or Date Formatters section of the Data Formatting Guide). You can then try converting using all of the permutations of the dateFormat string until you get a valid date.

Alternatively, you can use NSDataDetector:

NSError *error;
NSDataDetector *detector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeDate error:&error];
NSString *string = @"May 22, 2000";

NSTextCheckingResult *match = [detector firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
NSLog(@"date = %@", [match date]);

string = @"May 3 2000";

match = [detector firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
NSLog(@"date = %@", [match date]);

The above will find and recognize either of the date formats you suggested. There are limits as to what it can do, but sometimes it's useful.

Upvotes: 1

user3675069
user3675069

Reputation: 53

there is NSDate formatter

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

these links may help you

Upvotes: 0

navkast
navkast

Reputation: 468

If you know the string date format, you can use NSDateFormatter:

NSString *dateStr = @"Mon, 28 May 2014 1:31:38"; //A date string with a known format
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateStr]; 

The date variable above will give you the objective-c object that represents the date. You can look at various formats in Apple's guides or in other websites on the internet

Upvotes: 1

Related Questions