Về cơ bản, như tiêu đề nói. Tôi đang tự hỏi làm thế nào tôi có thể thêm 1 ngày vào một NSDate.
Vì vậy, nếu nó là:
21st February 2011
Nó sẽ trở thành:
22nd February 2011
Hoặc nếu đó là:
31st December 2011
Nó sẽ trở thành:
1st January 2012.
Về cơ bản, như tiêu đề nói. Tôi đang tự hỏi làm thế nào tôi có thể thêm 1 ngày vào một NSDate.
Vì vậy, nếu nó là:
21st February 2011
Nó sẽ trở thành:
22nd February 2011
Hoặc nếu đó là:
31st December 2011
Nó sẽ trở thành:
1st January 2012.
Câu trả lời:
Swift 5.0:
var dayComponent = DateComponents()
dayComponent.day = 1 // For removing one day (yesterday): -1
let theCalendar = Calendar.current
let nextDate = theCalendar.date(byAdding: dayComponent, to: Date())
print("nextDate : \(nextDate)")
Mục tiêu C:
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];
NSLog(@"nextDate: %@ ...", nextDate);
Điều này nên được tự giải thích.
dateByAddingComponents cuộc gọi thànhNSCalendarOptions(rawValue: 0)
Kể từ iOS 8, bạn có thể sử dụng NSCalendar.dateByAddingUnit
Ví dụ trong Swift 1.x:
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
.dateByAddingUnit(
.CalendarUnitDay,
value: 1,
toDate: today,
options: NSCalendarOptions(0)
)
Swift 2.0:
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
.dateByAddingUnit(
.Day,
value: 1,
toDate: today,
options: []
)
Swift 3.0:
let today = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)
date.add(.days, 1)nào? * đi và xây dựng một phần mở rộng
extension Date { func adding(_ component: Calendar.Component, _ value: Int) -> Date? { return Calendar.current.date(byAdding: component, value: value, to: self) } }cách sử dụngDate().adding(.day, 1) // "Jun 6, 2019 at 5:35 PM"
Đã cập nhật cho Swift 5
let today = Date()
let nextDate = Calendar.current.date(byAdding: .day, value: 1, to: today)
Mục tiêu C
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// now build a NSDate object for the next day
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: [NSDate date] options:0];
iOS 8+, OSX 10.9+, Objective-C
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay
value:1
toDate:[NSDate date]
options:0];
Một lao động thực hiện Swift 3+ dựa trên highmaintenance của câu trả lời và vikingosegundo của nhận xét. Tiện ích mở rộng Ngày này cũng có các tùy chọn bổ sung để thay đổi năm, tháng và thời gian:
extension Date {
/// Returns a Date with the specified amount of components added to the one it is called with
func add(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
let components = DateComponents(year: years, month: months, day: days, hour: hours, minute: minutes, second: seconds)
return Calendar.current.date(byAdding: components, to: self)
}
/// Returns a Date with the specified amount of components subtracted from the one it is called with
func subtract(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
return add(years: -years, months: -months, days: -days, hours: -hours, minutes: -minutes, seconds: -seconds)
}
}
Việc sử dụng chỉ thêm một ngày theo yêu cầu của OP sau đó sẽ là:
let today = Date() // date is then today for this example
let tomorrow = today.add(days: 1)
let foo = Date().add([.calendar: 1, .yearForWeekOfYear: 3] tôi đang thêm giải pháp thay thế cho câu trả lời của mình . Cảm ơn đề xuất của bạn, @vikingosegundo!
Swift 4.0 (giống như Swift 3.0 trong câu trả lời tuyệt vời này chỉ làm rõ cho những tân binh như tôi)
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
Sử dụng chức năng dưới đây và sử dụng thông số ngày để lấy ngày ngày Đầu / ngày. Chỉ cần truyền tham số là dương cho ngày trong tương lai hoặc âm cho ngày trước:
+ (NSDate *) getDate:(NSDate *)fromDate daysAhead:(NSUInteger)days
{
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = days;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *previousDate = [calendar dateByAddingComponents:dateComponents
toDate:fromDate
options:0];
[dateComponents release];
return previousDate;
}
Đó là công việc!
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit unit = NSCalendarUnitDay;
NSInteger value = 1;
NSDate *today = [NSDate date];
NSDate *tomorrow = [calendar dateByAddingUnit:unit value:value toDate:today options:NSCalendarMatchStrictly];
NSDate *today=[NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components=[[NSDateComponents alloc] init];
components.day=1;
NSDate *targetDate =[calendar dateByAddingComponents:components toDate:today options: 0];
Swift 4.0
extension Date {
func add(_ unit: Calendar.Component, value: Int) -> Date? {
return Calendar.current.date(byAdding: unit, value: value, to: self)
}
}
Sử dụng
date.add(.day, 3)! // adds 3 days
date.add(.day, -14)! // subtracts 14 days
Lưu ý: Nếu bạn không biết lý do tại sao các dòng mã kết thúc bằng dấu chấm than, hãy tìm kiếm "Tùy chọn Swift" trên Google.
Bạn có thể sử dụng phương pháp NSDate của - (id)dateByAddingTimeInterval:(NSTimeInterval)secondsnơi secondssẽ60 * 60 * 24 = 86400
Trong Swift 2.1.1 và xcode 7.1 OSX 10.10.5, bạn có thể thêm bất kỳ số ngày chuyển tiếp và lùi bằng cách sử dụng chức năng
func addDaystoGivenDate(baseDate:NSDate,NumberOfDaysToAdd:Int)->NSDate
{
let dateComponents = NSDateComponents()
let CurrentCalendar = NSCalendar.currentCalendar()
let CalendarOption = NSCalendarOptions()
dateComponents.day = NumberOfDaysToAdd
let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: baseDate, options: CalendarOption)
return newDate!
}
chức năng gọi để tăng ngày hiện tại thêm 9 ngày
var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9)
print(newDate)
chức năng gọi cho ngày giảm giá hiện tại của 80 ngày
newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80)
print(newDate)
Dưới đây là phương pháp mục đích chung cho phép bạn thêm / bớt bất kỳ loại đơn vị nào (Năm / Tháng / Ngày / Giờ / Giây, v.v.) trong ngày đã chỉ định.
Sử dụng Swift 2.2
func addUnitToDate(unitType: NSCalendarUnit, number: Int, date:NSDate) -> NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(
unitType,
value: number,
toDate: date,
options: NSCalendarOptions(rawValue: 0))!
}
print( addUnitToDate(.Day, number: 1, date: NSDate()) ) // Adds 1 Day To Current Date
print( addUnitToDate(.Hour, number: 1, date: NSDate()) ) // Adds 1 Hour To Current Date
print( addUnitToDate(.Minute, number: 1, date: NSDate()) ) // Adds 1 Minute To Current Date
// NOTE: You can use negative values to get backward values too
NSDateComponents *dayComponent = [[[NSDateComponents alloc] init] autorelease];
dayComponent.day = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];
Ok - tôi nghĩ rằng điều này sẽ làm việc cho tôi. Tuy nhiên, nếu bạn sử dụng nó để thêm một ngày vào ngày 31 tháng 3 năm 2013, nó sẽ trả về một ngày chỉ có 23 giờ được thêm vào đó. Nó thực sự có thể có 24, nhưng sử dụng trong tính toán chỉ có 23:00 giờ được thêm vào.
Tương tự, nếu bạn chuyển tiếp đến ngày 28 tháng 10 năm 2013, mã sẽ thêm 25 giờ dẫn đến thời gian ngày 2013-10-28 01:00:00.
Để thêm một ngày tôi đã làm việc ở trên cùng, thêm:
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
Phức tạp, chủ yếu là do tiết kiệm ánh sáng ban ngày.
60*60*24 + 1vì giây nhuận. ngày phải bao gồm tất cả những điều này, và đó là lý do tại sao việc xử lý ngày của ca cao thực sự là tuyệt vời!
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *tomorrowDate = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE, dd MMM yyyy"];
NSLog(@"%@", [dateFormatter stringFromDate:tomorrowDate]);
Trong swift, bạn có thể tạo tiện ích mở rộng để thêm phương thức trong NSDate
extension NSDate {
func addNoOfDays(noOfDays:Int) -> NSDate! {
let cal:NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(abbreviation: "UTC")!
let comps:NSDateComponents = NSDateComponents()
comps.day = noOfDays
return cal.dateByAddingComponents(comps, toDate: self, options: nil)
}
}
bạn có thể sử dụng nó như là
NSDate().addNoOfDays(3)
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
NSLog(@"StartDate = %@", startDate);
components.day += 1;
NSDate *endDate = [calendar dateFromComponents:components];
NSLog(@"EndDate = %@", endDate);
Tôi đã từng gặp vấn đề tương tự; sử dụng tiện ích mở rộng cho NSDate:
- (id)dateByAddingYears:(NSUInteger)years
months:(NSUInteger)months
days:(NSUInteger)days
hours:(NSUInteger)hours
minutes:(NSUInteger)minutes
seconds:(NSUInteger)seconds
{
NSDateComponents * delta = [[[NSDateComponents alloc] init] autorelease];
NSCalendar * gregorian = [[[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian] autorelease];
[delta setYear:years];
[delta setMonth:months];
[delta setDay:days];
[delta setHour:hours];
[delta setMinute:minutes];
[delta setSecond:seconds];
return [gregorian dateByAddingComponents:delta toDate:self options:0];
}
Swift 2.0
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)
Trong swift 4 hoặc swift 5, bạn có thể sử dụng như dưới đây:
let date = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: date)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let yesterday_date = dateFormatter.string(from: yesterday!)
print("yesterday->",yesterday_date)
đầu ra:
Current date: 2020-03-02
yesterday date: 2020-03-01
Mở rộng chuỗi: Chuyển đổi String_Date> Ngày
extension String{
func DateConvert(oldFormat:String)->Date{ // format example: yyyy-MM-dd HH:mm:ss
let isoDate = self
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = oldFormat
return dateFormatter.date(from:isoDate)!
}
}
Gia hạn ngày: Chuyển đổi ngày> Chuỗi
extension Date{
func DateConvert(_ newFormat:String)-> String{
let formatter = DateFormatter()
formatter.dateFormat = newFormat
return formatter.string(from: self)
}
}
Gia hạn ngày: Nhận +/- Ngày
extension String{
func next(day:Int)->Date{
var dayComponent = DateComponents()
dayComponent.day = day
let theCalendar = Calendar.current
let nextDate = theCalendar.date(byAdding: dayComponent, to: Date())
return nextDate!
}
func past(day:Int)->Date{
var pastCount = day
if(pastCount>0){
pastCount = day * -1
}
var dayComponent = DateComponents()
dayComponent.day = pastCount
let theCalendar = Calendar.current
let nextDate = theCalendar.date(byAdding: dayComponent, to: Date())
return nextDate!
}
}
Sử dụng:
let today = Date()
let todayString = "2020-02-02 23:00:00"
let newDate = today.DateConvert("yyyy-MM-dd HH:mm:ss") //2020-02-02 23:00:00
let newToday = todayString.DateConvert(oldFormat: "yyyy-MM-dd HH:mm:ss")//2020-02-02
let newDatePlus = today.next(day: 1)//2020-02-03 23:00:00
let newDateMinus = today.past(day: 1)//2020-02-01 23:00:00
tham khảo: từ nhiều câu hỏi
Làm cách nào để thêm 1 ngày vào NSDate?
Hàm toán học để chuyển int dương thành âm và âm thành dương?
Chuyển đổi NSString thành NSDate (và quay lại)
Sử dụng mã sau:
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
Như
addTimeInterval
bây giờ không được dùng nữa