0

我有一些对日期进行操作的代码。为了看看它是否可行,我为 OSX 控制台编写了一个非常简单的程序。它工作正常!但是,我想开始制作一个应用程序,所以我在基于视图的应用程序的函数中使用了相同的代码。但是,我不断收到一条错误消息:“没有已知的类方法 dateWithFormat。” 任何帮助,将不胜感激!

-(id)calc:(int)m with:(int)d andWith:(int)y {


 NSDateFormatter *formatter = [NSDateFormatter new];
    NSDate *date1 =[formatter setDateFormat:[NSString stringWithFormat:@"%i-%i-%i 00:00:00 +0000",m,d,y]];
    NSDate *date2 = [NSDate date];
    NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
    int numberOfDays = secondsBetween/86400;
 }
4

1 回答 1

3

首先:在您的代码段中,您不使用+dateWithFormat: (NSDate), 但是+dateWithString: (NSDate). 错字?请重新检查一下。+dateWithFormat: (NSDate)在 Mac OS 和 iOS 上不存在。

第二:-dateWithString: (NSDate)在 iOS 上不可用。这是一种方便的方法。使用日期格式化程序将字符串转换为日期。(这也是 Mac OS 上更好的方法。)

第三,更新您的评论:您的代码不应该编译:

NSDate *date1 = [NSDate dateWithString:@"%i-%i-%i 00:00:00 +0000",1,2,3];

Too many arguments to method call, expected 1, have 4

可能你想做这样的事情:

NSDate *date1 = [NSDate dateWithString:[NSString stringWithFormat:@"%i-%i-%i 00:00:00 +0000",1,2,3]];

如果您想在日期的组件上创建具有特定值的日期,请查看NSDatComponents

于 2013-05-18T05:27:29.117 回答