UFO ET IT

목표 C-두 날짜 사이의 일수 계산

ufoet 2020. 12. 26. 15:47
반응형

목표 C-두 날짜 사이의 일수 계산


중복 가능성 :
두 날짜를 어떻게 비교하고 일 수를 반환 할 수 있습니까?

두 개의 날짜 ( "yyyy-mm-dd"형식의 NSString)가 있습니다. 예를 들면 다음과 같습니다.

NSString *start = "2010-11-01";
NSString *end = "2010-12-01";

구현하고 싶습니다.

- (int)numberOfDaysBetween:(NSString *)startDate and:(NSString *)endDate {

}

감사!


NSString *start = @"2010-09-01";
NSString *end = @"2010-12-01";

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
                                                    fromDate:startDate
                                                      toDate:endDate
                                                     options:0];

components 이제 차이가 있습니다.

NSLog(@"%ld", [components day]);

날짜 및 시간 프로그래밍에 대한 전체 가이드가 있습니다. 다음은 수행 할 작업에 대한 힌트를 제공 하는 관련 섹션 입니다.

다른 질문에서 예제 코드의 출처입니다.

그것을 바탕으로 무언가를 시도하고 작성하고 구체적인 질문이 있으면 다시 오십시오.

편집하다

괜찮아. 가장 기본적인 형식으로 코드를 작성하는 방법은 다음과 같습니다.

먼저 NSDate를 확장합니다.

헤더 파일 :

//  NSDate+ADNExtensions.h

#import <Cocoa/Cocoa.h>


@interface NSDate (ADNExtensions)

- (NSInteger)numberOfDaysUntil:(NSDate *)aDate;

@end

구현 파일 :

//  NSDate+ADNExtensions.m

#import "NSDate+ADNExtensions.h"


@implementation NSDate (ADNExtensions)


- (NSInteger)numberOfDaysUntil:(NSDate *)aDate {
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:self toDate:aDate options:0];

    return [components day];
}


@end

이것은 매우 거친 코드입니다. 두 번째 날짜가 첫 번째 날짜보다 이후인지 확인하거나 확인하는 오류는 없습니다.

And then I would use it like this (running on a 64-bit, Garbage Collected environment):

NSDate *startDate = [NSDate dateWithString:@"2010-11-01 00:00:00 +0000"];
NSDate *endDate = [NSDate dateWithString:@"2010-11-02 00:00:00 +0000"];

NSInteger difference = [startDate numberOfDaysUntil:endDate];

NSLog(@"Diff = %ld", difference);

This is such a shame, because you would have learned a lot more by posting your code and the incorrect outputs and getting more specific help. But if you just want to be a cut-and-paste programmer; take this code and good luck to you.


This code seems to work nicely in Swift 2:

func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
    let calendar = NSCalendar.currentCalendar()

    let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])

    return components.day
}

Swift 4 implementation

Method call :

let numberOfDays = daysBetweenDates(startDate: fileCreatedDate,endDate: date)

Method Implementation:

 func daysBetweenDates(startDate: Date, endDate: Date) -> Int {
        let daysBetween = Calendar.current.dateComponents([.day], from: startDate, to: endDate)
        print(daysBetween.day!)
        return daysBetween.day!
  }

Objective C implementation:

Method Call:

int numberOfDaysSinceFileCreation = [self daysBetweenDates: fileCreatedDate
                                                                   currentDate: today];

Method Implementation:

- (int) daysBetweenDates: (NSDate *)startDate currentDate: (NSDate *)endDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponent = [calendar components:NSCalendarUnitDay fromDate:startDate toDate:endDate options:0];

    int totalDays = (int)dateComponent.day;
    return totalDays;

}

ObjC Code:

NSDateComponents *dateComponent = [calender components:NSCalendarUnitDay fromDate:startDate toDate:endDate options:0];

Result:

int totalDays = (int)dateComponent.day;

Swift 3:

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let start = formatter.date(from: "2010-09-01")!
let end = formatter.date(from: "2010-12-01")!
let days = Calendar.current.dateComponents([.day], from: start, to: end).day!

ReferenceURL : https://stackoverflow.com/questions/4575689/objective-c-calculating-the-number-of-days-between-two-dates

반응형