투케이2K

193. (Objective-C/objc) [간단 소스] DateComponents 사용해 현재 날짜 및 시간에서 특정 시간 더하기 및 빼기 수행 본문

Objective-C

193. (Objective-C/objc) [간단 소스] DateComponents 사용해 현재 날짜 및 시간에서 특정 시간 더하기 및 빼기 수행

투케이2K 2025. 4. 5. 09:03

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : OBJECTIVE-C

 

[소스 코드]

// --------------------------------------------------------------------------------------
[개발 및 테스트 환경]
// --------------------------------------------------------------------------------------

- 언어 : Objective-c

- 개발 툴 : Xcode

- 기술 구분 : objc / DateComponents / 날짜 계산

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[소스 코드]
// --------------------------------------------------------------------------------------

dispatch_async(dispatch_get_main_queue(), ^{
            
    // 현재 날짜와 시간 가져오기
    NSDate *currentDate = [NSDate date];
    
    
    // 추가할 연, 월, 일, 시간, 분, 초 설정
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear: 5]; // 연
    [components setMonth: 0]; // 월
    [components setDay: 0]; // 일
    [components setHour: 0]; // 시
    [components setMinute: 0]; // 분
    [components setSecond: 0]; // 초
    
    
    // 현재 날짜에 시간 추가하기
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *newDate = [calendar dateByAddingComponents:components toDate:currentDate options:0];
    
    
    // 결과 출력
    NSLog(@"현재 날짜 및 시간 : %@", currentDate);
    NSLog(@"계산 한 날짜 및 시간 : %@", newDate);
    
});

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[결과 출력]
// --------------------------------------------------------------------------------------

현재 날짜 및 시간 : 2025-04-05 00:00:08 +0000
계산 한 날짜 및 시간 : 2030-04-05 00:00:08 +0000

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[참고 사이트]
// --------------------------------------------------------------------------------------

https://blog.naver.com/kkh0977/222535389940?trackingCode=blog_bloghome_searchlist

https://blog.naver.com/kkh0977/222934137667?trackingCode=blog_bloghome_searchlist

// --------------------------------------------------------------------------------------
 
반응형
Comments