Arnlee Vizcayno
Arnlee Vizcayno

Reputation: 2426

iOS Time Stamp computation

I would like to know if there are other better time stamp computation in iOS and may i know your opinion about this computation weather there are issues or wrong with this computation.

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];

    NSDate * startDate = [formatter dateFromString:dateString];
    NSTimeInterval interval = [startDate timeIntervalSinceNow];

    int totalSeconds = abs((int)interval);

    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    int days = totalSeconds / (60 * 60 * 24);
    int weeks = totalSeconds / (60 * 60 * 24 * 7);
    int months = totalSeconds / (60 * 60 * 24 * 7 * 4);
    int years = totalSeconds / (60 * 60 * 24 * 7 * 4 * 12);

Your replies are much appreciated.

Upvotes: 0

Views: 311

Answers (3)

Anupdas
Anupdas

Reputation: 10201

Try

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];

NSDate * startDate = [formatter dateFromString:dateString];

NSCalendar *calender = [NSCalendar currentCalendar];

unsigned units = (NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|
             NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit);
NSDateComponents *dateComponents = [calender components:units
                                               fromDate:startDate];

int seconds = dateComponents.second;
int minutes = dateComponents.minute;
int hours   = dateComponents.hour;
int days    = dateComponents.day;
int weeks   = dateComponents.week;
int months  = dateComponents.month;
int years   = dateComponents.year;

Upvotes: 1

Marcin Kuptel
Marcin Kuptel

Reputation: 2664

You should try using the NSCalendar class and its method:

- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)date

For example:

NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponentes *components = [calendar components: unitFlags fromDate: date];

Upvotes: 0

rckoenes
rckoenes

Reputation: 69479

NSDateComponents is what you are looking for.

Upvotes: 1

Related Questions