NSDate but not NSTime how to convert string representation of time (no date)

My problem is that I want to have a way to represent the time (without a date), for example, the time of day in an iOS application. From the REST api, I get strings like β€œ13:12:11” that show the time when something happens, I used NSDateFormatter to convert NSStrings to NSDates, but as far as I can tell, it does not accept date formats with only time components for example HH:mm:ss [EDIT: you can, see below]

So my questions are 1- Is NSTimeInterval (instead of NSDate) what should I use to store the time of day?
2- How can I convert the object "03:04:05" to and objective-c from one of the built-in frameworks.

EDIT:. You can use formats such as "HH: mm: ss", it just replaces the date with 2000-01-01 Nevertheless, it would be very nice to have a date-independent presentation time of the day.

+4
source share
3 answers

OK, thanks everyone, here is what I did:

 NSString * timeAsString = "12:26:07"; NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"HH:mm:ss"]; NSDate * dateZero = [dateFormatter dateFromString:@"00:00:00"]; NSDate * dc = [dateFormatter dateFromString:timeAsString]; NSTimeInterval startTime = [dc timeIntervalSinceDate:dateZero]; 

This is not an elegant solution, but it works, at least for what I need to do,

+6
source

You can use NSDateComponent to create dates based on time. You can add values ​​per year based on the current date or future / past date.

 NSDateComponents *component=[[NSDateComponents alloc] init]; [component setHour:yourHour]; [component setMinute:yourMinutes]; [component setYear:yourYear]; [component setMonth:yourMonth]; [component setDay:yourDaty]; NSCalendar *calendar=[NSCalendar currentCalendar]; NSDate *date=[calendar dateFromComponents:component]; 
+4
source

NSDate * myDateVariable;

 NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [dateFormatter setTimeStyle:NSDateFormatterNoStyle]; //Not shown [someDateLabel setText:[dateFormatter stringFromDate:[myDateVariable]]]; //OR FOR BESPOKE FORMATTING NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"'Due' EEEE d MMM yyyy, h:mm a"]; [someDateLabel setText:[dateFormatter stringFromDate:[myDateVariable]]]; //Time using users 24/12 hour preference: [dateFormatter setDateFormat:@"HH:mm"]; //Time using 12 hour AM/PM format: [dateFormatter setDateFormat:@"h:mm a"]; //Day and date using abbreviated words: [dateFormatter setDateFormat:@"' ('EEE d MMM yyyy')'"]; //Day and date using full words: [dateFormatter setDateFormat:@"' ('EEEE d MMMM yyyy')'"]; 
0
source

Source: https://habr.com/ru/post/1436635/


All Articles