开发者社区> 问答> 正文

Swift IOS中月份和年份中两个NSData差异

我想计算月+年中两个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!)

能吗?

展开
收起
南南唐语 2019-12-04 20:51:27 914 0
1 条回答
写回答
取消 提交回答
  • 可以按照以下方式进行操作:

    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!))
      }
    }
    

    这是一种方法:

        let monthsCount = Calendar.current.dateComponents([.month], from: start, to: end).month! - 1
        guard monthsCount > 0 else { return [] }
        return (1...monthsCount).map {
            var monthYear = start
            monthYear.month! += $0
            let date = Calendar.current.date(from: monthYear)!
            let formatter = DateFormatter()
            formatter.dateFormat = "MMMM yyyy"
            return formatter.string(from: date)
        }
    }
    

    您应该DateComponents只将月份和年份组成部分传入此方法。您可以从这样的DateComponents对象中获取仅包含月份和年份的对象Date:```Calendar.current.dateComponents([.month, .year], from: someDate)

    2019-12-04 20:52:45
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关课程

更多

相关电子书

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