2011-04-14 13 views
12

Estoy tratando de evitar una validación de fecha que se niega a tomar nada antes que mañana.
Hasta ahora tengo esto:NSNúmero de NSDate

NSDate *dateY = [NSDate dateWithTimeIntervalSinceNow:-86400]; 
       // Negative one day, in seconds (-60*60*24) 
NSLog(@"%@", [NSDate date]); 
    // "yyyy-MM-dd HH:mm:ss Z", accurate assuming Z = +0000 
NSLog(@"%@", dateY); 
    // "yyyy-MM-dd HH:mm:ss Z", same accuracy (minus one day) 

Eso es grande, pero no es una dateYNSNumber. Necesito un NSNumber para la comparación, pero no puedo encontrar nada que funcione. (Yo no sé ni cómo un NSNumber puede haber 2011-04-14 13:22:29 +0000, de todos modos ...)

puedo usar para convertir un NSDateFormatterNSDate en un NSString, por lo que si sería posible tomar esa cadena y convertirlo en el requiere NSNumber (en lugar de convertir directamente el NSDate en un NSNumber, que parece que no encuentro ayuda con ninguno), estaría bien.


- (BOOL)validateDueDate:(id *)ioValue error:(NSError **)outError { 
    NSDate *dateY = [NSDate dateWithTimeIntervalSinceNow:-86400]; 
    NSNumber *tis1970 = [NSNumber numberWithDouble:[dateY timeIntervalSince1970]]; 
    NSLog(@"NSNumber From Date : %@", tis1970); 
    NSLog(@"Date From NSNumber : %@", [NSDate dateWithTimeIntervalSince1970:[tis1970 doubleValue]]); 

    // Due dates in the past are not valid 
    // Enforced that a due date has to be >= today's date 
    if ([*ioValue compare:[NSDate date]] == NSOrderedAscending) { 
     if (outError != NULL) { 
      NSString *errorStr = [[[NSString alloc] initWithString:@"Due date must be today or later."] autorelease]; 
      NSDictionary *userInfoDictionary = [NSDictionary dictionaryWithObject:errorStr forKey:@"ErrorString"]; 
      NSError *error = [[[NSError alloc] 
           initWithDomain:TASKS_ERROR_DOMAIN 
           code:DUEDATE_VALIDATION_ERROR_CODE 
           userInfo:userInfoDictionary] autorelease]; 
      *outError = error; 
      } 
     return NO; 
    } else { 
     return YES; 
    } 
} 

En este momento, el usuario no se le permite elegir una fecha antes de mañana. errorStr mentiras. Antes de hoy, tiene más sentido que el día de mañana como regla para negarse a guardar la fecha, así que he estado luchando con esto para permitirme usar ayer en lugar de hoy, en lugar de buscar algo más profundo.

Editar: El uso de NSOrderedSame permite seleccionar cualquier fecha sin un error. Eso no servirá.

+0

si quieres sólo para comparar la igualdad, se puede usar '[fecha isEqualToDate: dateY];' – Seega

+1

¿Por qué necesita un NSNumber para la comparación? ¿Ya tienes un NSNumber para comparar? ¿Que representa? –

+0

¿Qué es ioValue? ¿Un número? ¿Una cuerda? –

Respuesta

26

puede convertir un NSDate a un NSNumber así:

NSDate *aDate = [NSDate date]; 
NSNumber *secondsSinceRefDate = [NSNumber numberWithDouble:[aDate timeIntervalSinceReferenceDate]]; 

y convertir de nuevo como:

aDate = [NSDate dateWithTimeIntervalSinceReferenceDate:[NSNumber doubleValue]]; 
+0

para gente nueva (yo), al convertir de nuevo, el 'NSNumber' anterior es marcador de posición para su variable. Por ejemplo, el código anterior leería 'aDate = [NSDate dateWithTimeIntervalSinceReferenceDate: [secondsSinceRefDate doubleValue]];' // (gracias odrm) – tmr

1

Todo lo que se necesita para obtener un NSNumber es

NSDate *dateY = [NSDate dateWithTimeIntervalSinceNow:-86400]; 
NSNumber *tis1970 = [NSNumber numberWithDouble:[dateY timeIntervalSince1970]]; 
NSLog(@"NSNumber From Date : %@", tis1970); 
NSLog(@"Date From NSNumber : %@", [NSDate dateWithTimeIntervalSince1970:[tis1970 doubleValue]]); 
+0

Es más que probable que estés haciendo algo mal. Intenta copiar y pegar mi código. Voy a agregar una edición. Parece que está llamando a timeIntervalSinceReferenceData en un 'NSNumber' no en un' NSDate'. – Joe

+0

Agregue el código a su pregunta original. Necesitamos saber qué es ioValue y qué es lo que realmente está tratando de lograr. 'NSNumber' puede no ser la solución adecuada para usted. – Joe

+0

¡¡¡PUBLICA TU CÓDIGO !!!agregue seriamente su código, explique lo que está tratando de lograr y le puedo garantizar si es lógico que obtenga una solución adecuada. – Joe

1

Nunca debe usar 86400 t o calcule las diferencias de fecha, porque no todos los días tienen 86.400 segundos en ellas. NSDateComponents utilizar en su lugar:

- (BOOL)validateDueDate:(NSDate *)dueDate error:(NSError *)error { 
    NSDate *today = [NSDate date]; 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today]; 
    //adjust the components to tomorrow at the first instant of the day 
    [components setDay:[components day] + 1]; 
    [components setHour:0]; 
    [components setMinute:0]; 
    [components setSecond:0]; 
    NSDate *tomorrow = [calendar dateFromComponents:components]; 

    NSDate *earlierDate = [dueDate earlierDate:tomorrow]; 
    if ([earlierDate isEqualToDate:dueDate]) { 
    //the dueDate is before tomorrow 
    if (error != nil) { 
     NSString *errorStr = [[[NSString alloc] initWithString:@"Due date must be today or later."] autorelease]; 
     NSDictionary *userInfoDictionary = [NSDictionary dictionaryWithObject:errorStr forKey:NSLocalizedDescriptionKey]; 
     *error = [[[NSError alloc] initWithDomain:TASKS_ERROR_DOMAIN code:DUEDATE_VALIDATION_ERROR_CODE userInfo:userInfoDictionary] autorelease]; 
    } 
    return NO; 
    } 
    return YES; 
} 

ADVERTENCIA: código escrito en un navegador. Advertencia Implementor