Cách tính thời gian theo giờ giữa hai ngày trong iOS


103

Làm cách nào để tính thời gian trôi qua bằng giờ giữa hai thời điểm (có thể xảy ra vào các ngày khác nhau) trong iOS?


1
Một lựa chọn khác là sử dụng NSCalendar's -components:fromDate:toDate:options:phương pháp.
Thomas Müller

Tôi không tin rằng điều này sẽ cung cấp cho bạn một số giờ tuyệt đối. Nó sẽ chỉ cung cấp cho bạn một giá trị từ 0-24, nơi bạn phải dựa vào các thành phần Ngày, Tháng và Năm để có được khoảng thời gian đầy đủ.
codeperson

Tôi đã thử nghiệm điều này, và nó hoạt động tốt. Với từ Ngày 1/1/2012 và đến Ngày 4/1/2012, con số này đã trả về 96 giờ.
Thomas Müller

đăng mã của bạn Thomas? Nó không hoạt động đối với một số người.
John Riselvato

Câu trả lời:


171

Các NSDate chức năng timeIntervalSinceDate: sẽ cung cấp cho bạn sự khác biệt của hai thời điểm trong vài giây.

 NSDate* date1 = someDate;
 NSDate* date2 = someOtherDate;
 NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
 double secondsInAnHour = 3600;
 NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

Xem, thư viện tham khảo apple http://developer.apple.com/library/mac/navigation/ hoặc nếu bạn đang sử dụng Xcode, chỉ cần chọn trợ giúp / tài liệu từ menu.

Xem: how-to-convert-an-nstimeinterval-seconds-into-minutes

--edit: Xem câu trả lời của ÐąrέÐέvil dưới đây để xử lý chính xác thời gian tiết kiệm ánh sáng ban ngày / giây nhuận


2
Và điều gì sẽ xảy ra nếu ngày / giờ vượt qua quá trình chuyển đổi cho Tiết kiệm ánh sáng ban ngày?
Abizern

2
@Abizern: Cảm ơn, tôi đã không xem xét những trường hợp đó khi trả lời câu hỏi. Tôi đã liên kết với các câu trả lời bằng ÐąrέÐέvil
Akusete

tôi có khoảng thời gian như 4:50:30, h: m: si phải trừ thời gian này khỏi 12:30:20 như thế nào tôi sẽ làm điều này
AyAz

90
NSCalendar *c = [NSCalendar currentCalendar];
NSDate *d1 = [NSDate date];
NSDate *d2 = [NSDate dateWithTimeIntervalSince1970:1340323201];//2012-06-22
NSDateComponents *components = [c components:NSHourCalendarUnit fromDate:d2 toDate:d1 options:0];
NSInteger diff = components.minute;

NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit

Thay đổi các thành phần cần thiết thành ngày, giờ hoặc phút, sự khác biệt nào bạn muốn. Nếu NSDayCalendarUnitđược chọn thì nó sẽ trả về số ngày giữa hai ngày tương tự cho NSHourCalendarUnitNSMinuteCalendarUnit

Phiên bản Swift 4

let cal = Calendar.current
let d1 = Date()
let d2 = Date.init(timeIntervalSince1970: 1524787200) // April 27, 2018 12:00:00 AM
let components = cal.dateComponents([.hour], from: d2, to: d1)
let diff = components.hour!

DateWithTimeIntervalSince1970 chấp nhận giá trị nào? tôi tin rằng bạn đã chuyển đổi 2012-06-22 ngày thành 1340323201. Vui lòng sửa cho tôi.
Jeet

Không làm việc cho tôi. Có giá trị khác là 9223372036854775807. Giá trị đó tính bằng mili giây?
Kirti Nikam

Nhanh chóng 4.2. Thay vì [.hour], bạn có thể sử dụng Set <Calendar.Component> ([.
Hour

19
-(NSMutableString*) timeLeftSinceDate: (NSDate *) dateT {

    NSMutableString *timeLeft = [[NSMutableString alloc]init];

    NSDate *today10am =[NSDate date];

    NSInteger seconds = [today10am timeIntervalSinceDate:dateT];

    NSInteger days = (int) (floor(seconds / (3600 * 24)));
    if(days) seconds -= days * 3600 * 24;

    NSInteger hours = (int) (floor(seconds / 3600));
    if(hours) seconds -= hours * 3600;

    NSInteger minutes = (int) (floor(seconds / 60));
    if(minutes) seconds -= minutes * 60;

    if(days) {
        [timeLeft appendString:[NSString stringWithFormat:@"%ld Days", (long)days*-1]];
    }

    if(hours) {
        [timeLeft appendString:[NSString stringWithFormat: @"%ld H", (long)hours*-1]];
    }

    if(minutes) {
        [timeLeft appendString: [NSString stringWithFormat: @"%ld M",(long)minutes*-1]];
    }

    if(seconds) {
        [timeLeft appendString:[NSString stringWithFormat: @"%lds", (long)seconds*-1]];
    }

    return timeLeft;
}

9
Không, đừng làm điều này. Không phải tất cả các giờ đều có 3600 giây. Không phải tất cả các ngày đều có 24 giờ.
rmaddy

5
Điều này là hoàn toàn sai lầm. Không tính đến giây nhuận, tiết kiệm thời gian ban ngày. Vui lòng không phát minh lại bánh xe mà chỉ sử dụng các API được cung cấp với iOS như NSDateComponents.
Juan Catalan

5

Thanh toán: Nó quan tâm đến việc tiết kiệm ánh sáng ban ngày, năm nhuận vì nó đã sử dụng lịch iOS để tính toán. Bạn có thể thay đổi chuỗi và điều kiện để bao gồm phút với giờ và ngày.

+(NSString*)remaningTime:(NSDate*)startDate endDate:(NSDate*)endDate {

    NSDateComponents *components;
    NSInteger days;
    NSInteger hour;
    NSInteger minutes;
    NSString *durationString;

    components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute
                                                 fromDate: startDate toDate: endDate options: 0];
    days = [components day];
    hour = [components hour];
    minutes = [components minute];

    if (days > 0) {

        if (days > 1) {
            durationString = [NSString stringWithFormat:@"%d days", days];
        }
        else {
            durationString = [NSString stringWithFormat:@"%d day", days];
        }
        return durationString;
    }

    if (hour > 0) {

        if (hour > 1) {
            durationString = [NSString stringWithFormat:@"%d hours", hour];
        }
        else {
            durationString = [NSString stringWithFormat:@"%d hour", hour];
        }
        return durationString;
    }

    if (minutes > 0) {

        if (minutes > 1) {
            durationString = [NSString stringWithFormat:@"%d minutes", minutes];
        }
        else {
            durationString = [NSString stringWithFormat:@"%d minute", minutes];
        }
        return durationString;
    }

    return @"";
}

nó không hiển thị chênh lệch quá 12 giờ. Nếu tôi muốn kiểm tra một số điều kiện lúc 23 giờ, thì làm thế nào để có được sự chênh lệch giữa các thời điểm là 23 giờ?
Moxarth, 19/07/2017

Nó đưa ra khoảng thời gian sai, không hiệu quả với tôi.
Arvind Patel

3

Đối với những người sử dụng swift 3 trở lên,

    let dateString1 = "2018-03-15T14:20:00.000Z"
    let dateString2 = "2018-03-20T14:20:00.000Z"

    let Dateformatter = DateFormatter()
    Dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

    let date1 = Dateformatter.date(from: dateString1)
    let date2 = Dateformatter.date(from: dateString2)

    let distanceBetweenDates: TimeInterval? = date2?.timeIntervalSince(date1!)
    let secondsInAnHour: Double = 3600
    let secondsInDays: Double = 86400
    let secondsInWeek: Double = 604800

    let hoursBetweenDates = Int((distanceBetweenDates! / secondsInAnHour))
    let daysBetweenDates = Int((distanceBetweenDates! / secondsInDays))
    let weekBetweenDates = Int((distanceBetweenDates! / secondsInWeek))

    print(weekBetweenDates,"weeks")//0 weeks
    print(daysBetweenDates,"days")//5 days
    print(hoursBetweenDates,"hours")//120 hours
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.