Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C timespan

In C#, if I wanted to parse out a string into a date and timespan, I'd do something similar to the following:

String input = "08:00";
DateTime time;
if (!DateTime.TryParse(input, out time))
{
    // invalid input
    return;
}

TimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);

My Google-Fu has been less than desirable in finding a way to convert this to Objective-C.

Any suggestions?

like image 685
Saint Domino Avatar asked Aug 15 '26 11:08

Saint Domino


1 Answers

The Date and Time Programming Guide for Cocoa will likely be helpful for finding an approach that best fits your needs. I'd bet that NSDateComponents will be of particular interest — you can obtain an instance of this class from the -[NSCalendar components:fromDate:] method.

As far as getting the date from a string, one approach you could try is using NSDateFormatter, which has methods like -dateFromString: and -stringFromDate: to convert between NSString and NSDate representations. You can use -setDateFormat: to specify the format string to use for parsing. Once you have an NSDate object, you can also use one of its -timeIntervalSince... methods to get an NSTimeInterval which is a double value, measured in seconds.

like image 56
Quinn Taylor Avatar answered Aug 17 '26 00:08

Quinn Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!