Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get time and date by NSDate

how can I retrieve the date and time from a NSDate. I want to see them separately. thanks

like image 210
Safari Avatar asked Apr 16 '11 19:04

Safari


People also ask

How do I get the current date and time in Objective C?

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.

What is NSDate?

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.

How does Objective C compare to NSDate?

There are 4 methods for comparing NSDate s in Objective-C: - (BOOL)isEqualToDate:(NSDate *)anotherDate. - (NSDate *)earlierDate:(NSDate *)anotherDate. - (NSDate *)laterDate:(NSDate *)anotherDate.


2 Answers

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.

like image 108
Brodie Avatar answered Sep 22 '22 04:09

Brodie


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 ...

like image 41
Moszi Avatar answered Sep 20 '22 04:09

Moszi