2009-04-13 6 views

답변

38

시작하려면 Dates and Times Programming Topics for Cocoa을 읽어야합니다. 이것은 날짜의 고급 변환을 위해 Cocoa에서 제공되는 다양한 날짜/시간/달력 객체를 사용하는 것에 대한 좋은 이해를 줄 것입니다. 뿐만 아니라

- (NSInteger)currentHour 
{ 
    // In practice, these calls can be combined 
    NSDate *now = [NSDate date]; 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now]; 

    return [components hour]; 
} 
+0

찬성 투표. –

+0

+1 통화가 연결될 수 있음을 나타 내기 위해 – Abizern

+0

WWDC 비디오를 보면서 이번 주 NSHipster를 보는 것이 더 좋습니다. – uchuugaka

6

한 가지 방법은 필요에 따라 NSCalendar과 현재 시간 NSDateComponents

NSDate *now = [NSDate date]; 
NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now]; 
NSInteger hour = [components hour]; 
1
[NSDate date] 

, 시간을 구문 분석 사용하는 것입니다. 예를 들어 현재 시간대로 포맷 된 시간과 정확히 정확히 몇 시간 씩 상세하게 설명하지 않았습니까? 또는 다른 것?

2

나는 코코아에 새로운 오전, 나는 내가 이걸 발견 매우 기쁘다 :

이 코드 싹둑 그러나, 특정 문제에 대답 할 것이다. 또한이 함수를 하나의 NSDateComponents 객체에서 현재 시간, 분, 초를 반환하는 함수로 쉽게 만들 수 있다는 것을 포함하고자합니다. 이 같은 :

// Function Declaration (*.h file) 
-(NSDateComponents *)getCurrentDateTime:(NSDate *)date; 

// Implementation 
-(NSDateComponents *)getCurrentDateTime:(NSDate *)date 
{ 
    NSDate *now = [NSDate date]; 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSDateComponents *comps = [calendar components:NSHourCalendarUnit + NSMinuteCalendarUnit + NSSecondCalendarUnit fromDate:now]; 
    return comps; 

} 

// call and usage 

NSDateComponents *today = [self getCurrentDateTime:[NSDate date]]; 
     hour = [today hour]; 
     minute = [today minute]; 
     second = [today second]; 

당신은 NSCalendar 객체의 구성 요소 매개 변수가 비트 단위 열거입니다 확인하실 수 있으며, 사용하여 열거 값을 결합 할 수 있습니다 같이 '+'나는 이후

그냥 내가 기여할 것이라고 생각 예제를 사용하여 광산을 만들 수 있습니다.

0

스위프트 버전의 문서에 링크

func currentHour() -> Int { 
    let now = NSDate() 
    let calendar = NSCalendar.currentCalendar() 
    let components = calendar.components(.Hour, fromDate: now) 

    return components.hour 
} 
관련 문제