iphone - framework - xcode




Recuperando la hora local actual en iPhone? (5)

// 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);

Estoy buscando obtener la hora y los minutos actuales en el iPhone de un usuario para mostrarlos en una aplicación que no muestra la barra de estado. ¿Hay una manera simple de hacer esto?


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;

Creo que deberías probar esto. TimeZone es importante.


-(void)currentTime
{    
    //Get current time
    NSDate* now = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitHour  | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:now];
    NSInteger hour = [dateComponents hour];
    NSString *am_OR_pm[email protected]"AM";

    if (hour>12)
    {
        hour=hour%12;

        am_OR_pm = @"PM";
    }

    NSInteger minute = [dateComponents minute];
    NSInteger second = [dateComponents second];
    [gregorian release];

    NSLog(@"Current Time  %@",[NSString stringWithFormat:@"%02ld:%02ld:%02ld %@", (long)hour, (long)minute, (long)second,am_OR_pm]);
}

Un enfoque más corto

NSDate * now = [NSDate date];
timeLabel.text = [NSDateFormatter localizedStringFromDate:now
                                                dateStyle:NSDateFormatterNoStyle
                                                timeStyle:NSDateFormatterShortStyle];

Vea esta pregunta similar para una respuesta. Tendrá que cambiarlo a su formato de fecha.

[[NSDate date] timeIntervalSince1970];






cocoa-touch