2016-02-16 79 views
1

我試圖顯示當前的日期和時間。對於當前日期和時間運作良好,這是我的代碼:如何讓時間像(1 - 下午2點)或(2 - 下午3點)

NSDate *currDate = [NSDate date]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
    [dateFormatter setDateFormat:@"dd MMM YYYY hh:mm a"]; 
    NSString *dateString = [dateFormatter stringFromDate:currDate]; 

    _dateLabel.text=dateString; 

我需要的是什麼。我需要證明我的時間,如:

例如現在這個問題發佈時間是1:42pm。我想是這樣的:

1 - 下午2點

但對於上面的代碼我收到:1:42 pm。我需要這樣的:

1 - 2 pm 

請幫我怎麼做那個1小時的插槽。

謝謝!

回答

2
- (NSString *)dateString { 
    NSDate *currentDate = [NSDate date]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"dd MMM yyyy"]; 
    NSString *dateString = [dateFormatter stringFromDate:currentDate]; 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSDateComponents *components = [calendar components:NSCalendarUnitHour fromDate:currentDate]; 
    NSInteger hour = [components hour]; 
    NSInteger nextHour = [components hour] + 1; 
    NSString *nextHourDateString = @""; 
    if (nextHour == 24) { 
     nextHour = 0; 
     NSTimeInterval oneHour = 60 * 60; 
     NSDate *nextHourDate = [NSDate dateWithTimeInterval:oneHour sinceDate:currentDate]; 
     nextHourDateString = [[dateFormatter stringFromDate:nextHourDate] stringByAppendingString:@" "]; 
    } 
    NSString *hourSuffix = hour > 12 ? @" pm" : @" am"; 
    NSString *nextHourSuffix = nextHour > 12 ? @" pm" : @" am"; 
    if ([hourSuffix isEqualToString:nextHourSuffix]) { 
     hourSuffix = @""; 
    } 
    return [NSString stringWithFormat:@"%@ %ti%@ - %@%ti%@", 
             dateString, 
             [self hourInTwelveHourFormat:hour], 
             hourSuffix, 
             nextHourDateString, 
             [self hourInTwelveHourFormat:nextHour], 
             nextHourSuffix];; 
} 

- (NSInteger)hourInTwelveHourFormat:(NSInteger)hour { 
    if (hour > 12) { 
     hour -= 12; 
    } 
    return hour; 
} 
+0

其顯示14-15下午 – user5513630

+0

是的,忘記了下午,我編輯了我的答案。你也應該在下午11點到凌晨0點處理一個案子。 –

+0

它可能顯示在我的代碼中。因爲我需要在單行 – user5513630

相關問題