Retrieving current local time on iPhone?

后端 未结 7 559
我寻月下人不归
我寻月下人不归 2020-12-01 07:57

I\'m looking to get the current hour and minute on a user\'s iPhone for display in an app that doesn\'t show the status bar. Is there a simple way to do this?

相关标签:
7条回答
  • 2020-12-01 08:10

    See this similar question for an answer. You will have to change it to your date format.

    [[NSDate date] timeIntervalSince1970];
    0 讨论(0)
  • 2020-12-01 08:11

    A shorter approach

    NSDate * now = [NSDate date];
    timeLabel.text = [NSDateFormatter localizedStringFromDate:now
                                                    dateStyle:NSDateFormatterNoStyle
                                                    timeStyle:NSDateFormatterShortStyle];
    
    0 讨论(0)
  • 2020-12-01 08:15

    CFAbsoluteTimeGetCurrent()

    Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.

    0 讨论(0)
  • 2020-12-01 08:18
    // get current date/time
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *currentTime = [dateFormatter stringFromDate:today];
    [dateFormatter release];
    NSLog(@"User's current time in their preference format:%@",currentTime);
    
    0 讨论(0)
  • 2020-12-01 08:23

    if you are looking to calculate time intervals, you are better off using CACurrentMediaTime

    double currentTime = CACurrentMediaTime();
    
    0 讨论(0)
  • 2020-12-01 08:25
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]]
    [dateFormatter release]; dateFormatter = nil;
    

    I think you should try this. The timeZone is important.

    0 讨论(0)
提交回复
热议问题