How to get 1 hour ago from a date in iOS swift?

前端 未结 13 752
一向
一向 2020-12-04 13:35

I have been researching, but I couldnt find exact solution for my problem. I have been trying to get 1 hour ago from a date. How can I achieve this in swift?

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 13:57

    For correct calculations involving NSDate that take into account all edge cases of different calendars (e.g. switching between day saving time) you should use NSCalendar class:

    Swift 3+

    let earlyDate = Calendar.current.date(
      byAdding: .hour, 
      value: -1, 
      to: Date())
    

    Older

    // Get the date that was 1hr before now
    let earlyDate = NSCalendar.currentCalendar().dateByAddingUnit(
           .Hour,
           value: -1, 
           toDate: NSDate(),
           options: [])
    

提交回复
热议问题