objective-c 如何向 NSDate 添加小时数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1654393/
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-03 22:26:44  来源:igfitidea点击:

How to add hours to an NSDate?

objective-ciphone-sdk-3.0nsdate

提问by Rahul Vyas

I have a date converted to double value and saved in database. Now, I want to compare if currentDate > myDataBaseDate + 8hours i.e., I want to get 8 hours added to myDataBaseDate. I'm converting date into double values. So how do I get 8 hours later time from my database saved date. How do I compare

我有一个日期转换为双精度值并保存在数据库中。现在,我想比较currentDate > myDataBaseDate + 8小时,即,我想将 8 小时添加到 myDataBaseDate。我正在将日期转换为双精度值。那么如何从我的数据库保存日期中获得 8 小时后的时间。我如何比较

if (currentDateTime > DateFromdatabaseValue + DateByAdding8HoursInDataBase)

回答by Tom Jefferys

I'm not entirely sure what you are trying to do, but you can create an NSDate object by adding time in seconds on to another NSDate using:

我不完全确定您要做什么,但是您可以通过使用以下方法将时间(以秒为单位)添加到另一个 NSDate 来创建 NSDate 对象:

- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds

- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds

// eg. to add 8 hours to current time:

// 例如。将 8 小时添加到当前时间:

NSDate *mydate = [NSDate date];
NSTimeInterval secondsInEightHours = 8 * 60 * 60;
NSDate *dateEightHoursAhead = [mydate dateByAddingTimeInterval:secondsInEightHours];

回答by Ben Packard

Since iOS 8 there is the more convenient dateByAddingUnit:

由于 iOS 8 有更方便的dateByAddingUnit

//add 8 hours
let calendar = NSCalendar.autoupdatingCurrentCalendar()
newDate = calendar.dateByAddingUnit(.CalendarUnitHour, value: 8, toDate: originalDate, options: nil)

回答by TechSeeko

You can simply use:

您可以简单地使用:

NSDate *incrementedDate = [NSDate dateWithTimeInterval:numberOfSeconds sinceDate:[NSDate date]];

回答by Pascal

You can simply add 8 * 3600 to your database value (assuming that your converted double value represents seconds).

您可以简单地将 8 * 3600 添加到您的数据库值(假设您转换的双精度值代表秒)。

回答by Venu Gopal Tewari

NSDate *startdate = datePicker.date;

NSDate *startdate = datePicker.date;

    NSTimeInterval secondsInOneHours = 1 * 60 * 60;

    NSDate *dateOneHoursAhead = [startdate dateByAddingTimeInterval:secondsInOneHours];

    [dateformate setDateFormat:@"d-MMM-yy HH:mm:ss"];

    strDate = [dateformate stringFromDate:dateOneHoursAhead];

回答by SwiftDeveloper

Swift 3.XSimple usage

Swift 3.X简单使用

let calendar = NSCalendar.autoupdatingCurrent
let newDate = calendar.date(byAdding: .hour, value: 8, to: Date())