开发者社区> 问答> 正文

SWIFT IOS中两个NSD的月份和年份差异

我必须计算两个NSDate在月+年之间的时间。

例1:

Start Date: September 2018
End Date: May 2019

因此,我必须了解这两个日期之间的区别,只需显示最后6个月,如下所示:

April 2019
March 2019
February 2019
January 2019
December 2018
November 2018

例2:

Start Date: October 2019
End Date: December 2019```  
 
产出应是:

November 2019 October 2019

使用下面的代码,我可以在几个月内得到两个日期之间的区别:

let components = Calendar.current.dateComponents([.weekOfYear, .month], from: subscriptionDate!, to: currentDate!)

有人能帮我吗?

谢谢!

展开
收起
游客5akardh5cojhg 2019-12-04 16:31:22 426 0
1 条回答
写回答
取消 提交回答
  • 你可以这样做.

    //set start & end date in correct format
    let strStartDate = "September 2019"
    let strEndDate = "December 2019"
    
    //create date formatter
    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM yyyy"
    
    //convert string into date object
    guard let startDate = formatter.date(from: strStartDate) else {
      print("invalid start date")
       return
    }
    
     //convert string into date object
    guard let endDate = formatter.date(from: strEndDate) else {
      print("invalid end date time")
      return
    }
    
    //calculate the month from end date and that should not exceed the start date
    for month in 1...6 {
    
      if let dt = Calendar.current.date(byAdding: .month, value: -month, to: endDate) {
         if dt.compare(startDate) == .orderedAscending {
            break
          } 
          print(formatter.string(from: dt!))
      }
    }
    
    2019-12-04 16:32:07
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关课程

更多

相关电子书

更多
手淘iOS性能优化探索 立即下载
From Java/Android to Swift iOS 立即下载
深入剖析iOS性能优化 立即下载