xcode 来自 NSDate 的 NSNumber

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5664276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:50:01  来源:igfitidea点击:

NSNumber from NSDate

objective-cxcodensdatensnumber

提问by Thromordyn

I'm attempting to get around a date validation that refuses to take anything earlier than tomorrow.
So far I have this:

我正在尝试绕过拒绝在明天之前进行任何操作的日期验证。
到目前为止,我有这个:

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)

That's great, but dateYis not an NSNumber. I need an NSNumberfor the comparison, but I can't find anything that works. (I don't even know how an NSNumbercan be 2011-04-14 13:22:29 +0000, anyway...)

这很棒,但dateY不是NSNumber. 我需要一个NSNumber进行比较,但我找不到任何有效的东西。(我什至不知道怎么NSNumber可以2011-04-14 13:22:29 +0000,反正......)

I can use NSDateFormatterto convert an NSDateinto an NSString, so if it would be possible to take that string and convert it to the required NSNumber(as opposed to directly converting the NSDateto an NSNumber, which I can't seem to find help with either), that would be fine.

我可以使用NSDateFormatter将 an 转换NSDate为 an NSString,因此如果可以将该字符串转换为所需的NSNumber(而不是直接将 the 转换NSDate为 an NSNumber,我似乎无法找到任何帮助),那将没事的。



- (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;
    }
}

Right now, the user is not allowed to choose a date before tomorrow. errorStrlies. Before today makes more sense than before tomorrow as a rule for refusing to save the date, so I've been fighting with this thing to let me use yesterday in place of today, rather than looking any deeper.

目前,不允许用户选择明天之前的日期。errorStr谎言。作为拒绝保存日期的规则,今天之前比明天更有意义,所以我一直在与这个东西作斗争,让我用昨天代替今天,而不是更深入地研究。

Edit: Using NSOrderedSameallows any date to be selected without an error. That won't do.

编辑:使用NSOrderedSame允许选择任何日期而不会出错。那不行。

回答by odrm

You can convert an NSDateto an NSNumberlike this:

您可以像这样将 an 转换NSDate为 an NSNumber

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

and convert back like:

并转换回来,如:

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

回答by Joe

All that is needed to get a NSNumberis

获得 aNSNumber所需要的只是

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

回答by Dave DeLong

You should never use 86400to calculate date differences, because not all days have 86,400 seconds in them. Use NSDateComponentsinstead:

您永远不应该使用86400计算日期差异,因为并非所有的日子都有 86,400 秒。使用NSDateComponents来代替:

- (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;
}

WARNING: code typed in a browser. Caveat Implementor

警告:在浏览器中输入的代码。警告实施者