how can I retrieve the date and time from a NSDate. I want to see them separately. thanks
NSDate and NSDateFormatter classes provide the features of date and time. NSDateFormatter is the helper class that enables easy conversion of NSDate to NSString and vice versa. A simple example to show conversion of NSDate to NSString and back to NSDate is shown below.
The NSDate class provides methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date.
There are 4 methods for comparing NSDate s in Objective-C: - (BOOL)isEqualToDate:(NSDate *)anotherDate. - (NSDate *)earlierDate:(NSDate *)anotherDate. - (NSDate *)laterDate:(NSDate *)anotherDate.
NSDate *localDate = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; dateFormatter.dateFormat = @"MM/dd/yy"; NSString *dateString = [dateFormatter stringFromDate: localDate]; NSDateFormatter *timeFormatter = [[NSDateFormatter alloc]init]; timeFormatter.dateFormat = @"HH:mm:ss"; NSString *dateString = [timeFormatter stringFromDate: localDate];
There are many many different ways to represent the date and time so check NSDateFormatter for more info.
i would go with using NSDateComponents and NSCalendar if you really want to have the values for the minute, hour and the date ... Something like this:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
then you can use the properties of the components to access the value of each components with component.hour, component.year, etc.
Also please note that if you are going with the NSDateFormatter example - then you should remember that NSDateFormatter is a heavy object and you should really reuse it if possible ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With