How to use the current time in Objective-C

不羁岁月 提交于 2019-12-14 00:10:50

问题


How should I import the current time into my app and use it to do some calculation?

What my app do is that it use the current time and do some calculation and then give me some percentage.


回答1:


How are you wanting to get the time (in milliseconds?)

There's a few questions on here already - like this one, which should help point you in the right direction.

From the Apple Docs for NSDate

Creates and returns an NSDate object set to the given number of seconds from the first instant of 1 January 1970, GMT.

[[NSDate date] timeIntervalSince1970];




回答2:


// use this method to get current time as per your iPhone's time format
    +(NSString *)getCurrTime
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setLocale:[NSLocale currentLocale]];
        [formatter setDateStyle:NSDateFormatterNoStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
        NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];

        BOOL is24h = (amRange.location == NSNotFound && pmRange.location == NSNotFound);
        if (is24h == YES) {
            [formatter setDateFormat:@"HH:mm"];
        }
        else
        {
            [formatter setDateFormat:@"hh:mm a"];
        }
        dateString =[formatter stringFromDate:[NSDate date]];
        NSLog(@"%@\n",(is24h ? @"YES" : @"NO"));
        return dateString;
    }


来源:https://stackoverflow.com/questions/26417583/how-to-use-the-current-time-in-objective-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!