如何从Swift当年获得每月的一半

时间:2018-04-12 05:50:30

标签: ios swift date

在我的应用程序中,我可以选择每15天输入一次数据。我必须保留当前年份。请帮我弄清楚这个问题。 例如:[             “1-1-2018至15-1-2018”,“16-1-2018至31-1-2018”,             “1-2-2018至15-2-2018”,“16-2-2018至28-2-2018”,             “1-3-2018至15-3-2018”,“16-3-2018至31-3-2018”,             “1-4-2018至15-4-2018”,“16-4-2018至30-4-2018”,             “1-5-2018至15-5-2018”,“16-5-2018至31-5-2018”,             “1-6-2018至15-6-2018”,“16-6-2018至30-6-2018”,             “1-7-2018至15-7-2018”,“16-7-2018至31-7-2018”,             “1-8-2018至15-8-2018”,“16-8-2018至31-8-2018”,             “1-9-2018至15-9-2018”,“16-9-2018至30-9-2018”,             “1-10-2018至15-10-2018”,“16-10-2018至31-10-2018”,             “1-11-2018至15-11-2018”,“16-11-2018至30-11-2018”,             “1-12-2018至15-12-2018”,“16-12-2018至31-12-2018”         ]

2 个答案:

答案 0 :(得分:1)

Calendar API,您可以获得指定日期和月份第一天的总天数,如下所示

extension Calendar {

    public func firstDayOfMonth(date: Date) -> Date {
        let components = self.dateComponents([.year, .month], from: date)
        return  self.date(from: components) ?? date
    }

    public func numberOfDaysInMonthFor(date: Date) -> Int {
        let range = self.range(of: .day, in: .month, for: date)
        return range?.count ?? 0
    }

    public func lowerHalfOfMonthFor(date: Date) -> (Date, Date) {
        let startDate = self.firstDayOfMonth(date: date)
        let endDate = startDate.dateByAppending(day: 14)

        return (startDate, endDate)
    }

    public func upperHalfOfMonthFor(date: Date) -> (Date, Date) {
        let firstDayOfMonthDate = self.firstDayOfMonth(date: date)
        let totalNoOfDaysInMonth = self.numberOfDaysInMonthFor(date: firstDayOfMonthDate)

        let startDate = firstDayOfMonthDate.dateByAppending(day: 15)
        let endDate = firstDayOfMonthDate.dateByAppending(day: totalNoOfDaysInMonth - 1)

        return (startDate, endDate)
    }
}

您还可以通过追加任意天数来延长日期以获取新日期,

extension Date {

    public func dateByAppending(day: Int) -> Date {
        let newDate = Calendar.current.date(byAdding: .day, value: day, to: self)
        return newDate ?? self
    }

    public func daysDifference(_ date: Date?) -> Int? {
        guard let date = date else { return nil }
        return Calendar.current.dateComponents([.day], from: self, to: date).day
    }

通过混合使用上述辅助方法,您应该能够获得如下所示的结果,

let date = Date()
let lowerHalf = Calendar.current.lowerHalfOfMonthFor(date: date)
let uppperHalf = Calendar.current.upperHalfOfMonthFor(date: date)

答案 1 :(得分:0)

如果您提供输入,下面的代码将计算第15天

 static func getFortnightly(selectedDate : String) -> String?{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yy" //Your date format
    if let dateSelected = dateFormatter.date(from: selectedDate) {//according to d
      let newDate = Calendar.current.date(byAdding: .weekOfYear, value: 2, to: dateSelected)
      let convertedDateToString = dateFormatter.string(from: newDate!)
      return convertedDateToString
    }
    return nil
  }
}