Swift中的日期扩展3

时间:2016-09-05 16:44:39

标签: swift3 nscalendar

以下代码是日期扩展的一部分。然而,在Swift 3中,我得到了一些不会消失的错误。我已经改变了" NSCalendar"到"日历":

func startOfWeek(_ weekday: Int?) -> Date? {
    guard
        let cal = Calendar.current,
        let comp: DateComponents = (cal as Calendar).components([.yearForWeekOfYear, .weekOfYear], from: self) else { return nil }
    comp.to12pm()
    cal.firstWeekday = weekday ?? 1
    return cal.date(from: comp)!
}
func endOfWeek(_ weekday: Int) -> Date? {
    guard
        let cal = Calendar.current,
        var comp: DateComponents = (cal as Calendar).components([.weekOfYear], from: self) else { return nil }
    comp.weekOfYear = 1
    comp.day -= 1
    comp.to12pm()
    return (cal as NSCalendar).date(byAdding: comp, to: self.startOfWeek(weekday)!, options: [])!
}

第3行& 11:让cal = Calendar.current, 条件绑定的初始化程序必须具有可选类型,而不是'日历'

第12行:我遇到了错误,但通过更改"让comp:" to" var comp:"

第14行: comp.day - = 1 错误:二元运算符' - ='不能应用于类型' Int?'的操作数。和' Int'

我对扩展程序不太满意,这段代码是根据我在网上找到的扩展程序改编的,所以现在更新这个代码很难实现。有什么建议吗?

疑难解答(我尝试过的事情):

让cal = Calendar?.current,

错误:输入'日历?&#39>没有会员'当前'

让cal:日历? = Calendar.current,

错误:明确指定类型'日历?'为初始化程序添加了一个额外的可选级别,使可选检查始终成功

让cal = Calendar.current?,

错误:无法在类型'日历'

的非可选值上使用可选链接

2 个答案:

答案 0 :(得分:0)

基于@LeoDabus

的评论,我在Swift 3中的日期扩展
func startOfWeek(_ weekday: Int? = 1) -> Date? {
    var cal = Calendar.current
    cal.firstWeekday = weekday ?? 1
    let comp = cal.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
    comp.to12pm()
    return cal.date(from: comp)
}
func endOfWeek(_ weekday: Int) -> Date? {
    let cal = Calendar.current
    var comp = cal.dateComponents([.weekOfYear], from: self)
    comp.weekOfYear = 1
    comp.day? -= 1
    comp.to12pm()
    return cal.date(byAdding: comp, to: self.startOfWeek(weekday)!)!
}

注意我仍处于迁移中期,因此我只能确认这些消除了错误,并且无法在生产中对其进行测试。

答案 1 :(得分:0)

您可以使用此扩展程序单独获取每个日期组件:

extension Date {

// MARK:- APP SPECIFIC FORMATS

func app_dateFromString(strDate:String, format:String) -> Date? {

    let dateFormatter:DateFormatter = DateFormatter()
    dateFormatter.dateFormat = format
    if let dtDate = dateFormatter.date(from: strDate){
        return dtDate as Date?
    }
    return nil
}


func app_stringFromDate() -> String{
    let dateFormatter:DateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    let strdt = dateFormatter.string(from: self as Date)
    if let dtDate = dateFormatter.date(from: strdt){
        return dateFormatter.string(from: dtDate)
    }
    return "--"
}

func app_stringFromDate_timeStamp() -> String{
    return "\(self.hourTwoDigit):\(self.minuteTwoDigit) \(self.AM_PM)  \(self.monthNameShort) \(self.dayTwoDigit)"
}


func getUTCFormateDate(localDate: NSDate) -> String {

    let dateFormatter:DateFormatter = DateFormatter()
    let timeZone: NSTimeZone = NSTimeZone(name: "UTC")!
    dateFormatter.timeZone = timeZone as TimeZone!
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
    let dateString: String = dateFormatter.string(from: localDate as Date)
    return dateString
}


func combineDateWithTime(date: NSDate, time: NSDate) -> NSDate? {
    let calendar = NSCalendar.current


    let dateComponents = calendar.dateComponents([.year, .month, .day], from: date as Date)

    let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: time as Date)


    let mergedComponments = NSDateComponents()
    mergedComponments.year = dateComponents.year!
    mergedComponments.month = dateComponents.month!
    mergedComponments.day = dateComponents.day!
    mergedComponments.hour = timeComponents.hour!
    mergedComponments.minute = timeComponents.minute!
    mergedComponments.second = timeComponents.second!

    return calendar.date(from: mergedComponments as DateComponents) as NSDate?
}

func getDatesBetweenDates(startDate:NSDate, andEndDate endDate:NSDate) -> [NSDate] {
    let gregorian: NSCalendar = NSCalendar.current as NSCalendar;
    let components = gregorian.components(NSCalendar.Unit.day, from: startDate as Date, to: endDate as Date, options: [])
    var arrDates = [NSDate]()
    for i in 0...components.day!{
        arrDates.append(startDate.addingTimeInterval(60*60*24*Double(i)))
    }
    return arrDates
}


func isGreaterThanDate(dateToCompare: NSDate) -> Bool {
    //Declare Variables
    var isGreater = false

    //Compare Values
    if self.compare(dateToCompare as Date) == ComparisonResult.orderedDescending {
        isGreater = true
    }

    //Return Result
    return isGreater
}

func isLessThanDate(dateToCompare: Date) -> Bool {
    //Declare Variables
    var isLess = false

    //Compare Values
    if self.compare(dateToCompare as Date) == ComparisonResult.orderedAscending {
        isLess = true
    }

    //Return Result
    return isLess
}

func equalToDate(dateToCompare: NSDate) -> Bool {
    //Declare Variables
    var isEqualTo = false

    //Compare Values
    if self.compare(dateToCompare as Date) == ComparisonResult.orderedSame {
        isEqualTo = true
    }

    //Return Result
    return isEqualTo
}


// MARK:- TIME
var timeWithAMPM: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mma"
    dateFormatter.amSymbol = "am"
    dateFormatter.pmSymbol = "pm"
    return dateFormatter.string(from: self as Date)
}




// MARK:- YEAR


var yearFourDigit_Int: Int {
    return Int(self.yearFourDigit)!
}

var yearOneDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "y"
    return dateFormatter.string(from: self as Date)
}
var yearTwoDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yy"
    return dateFormatter.string(from: self as Date)
}
var yearFourDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy"
    return dateFormatter.string(from: self as Date)
}



// MARK:- MONTH

var monthOneDigit_Int: Int {
    return Int(self.monthOneDigit)!
}
var monthTwoDigit_Int: Int {
    return Int(self.monthTwoDigit)!
}


var monthOneDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "M"
    return dateFormatter.string(from: self as Date)
}
var monthTwoDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM"
    return dateFormatter.string(from: self as Date)
}
var monthNameShort: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM"
    return dateFormatter.string(from: self as Date)
}
var monthNameFull: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMMM"
    return dateFormatter.string(from: self as Date)
}
var monthNameFirstLetter: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMMMM"
    return dateFormatter.string(from: self as Date)
}

// MARK:- DAY

var dayOneDigit_Int: Int {
    return Int(self.dayOneDigit)!
}
var dayTwoDigit_Int: Int {
    return Int(self.dayTwoDigit)!
}

var dayOneDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "d"
    return dateFormatter.string(from: self as Date)
}
var dayTwoDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd"
    return dateFormatter.string(from: self as Date)
}
var dayNameShort: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "E"
    return dateFormatter.string(from: self as Date)
}
var dayNameFull: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.string(from: self as Date)
}
var dayNameFirstLetter: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEEE"
    return dateFormatter.string(from: self as Date)
}




// MARK:- AM PM
var AM_PM: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "a"
    return dateFormatter.string(from: self as Date)
}

// MARK:- HOUR


var hourOneDigit_Int: Int {
    return Int(self.hourOneDigit)!
}
var hourTwoDigit_Int: Int {
    return Int(self.hourTwoDigit)!
}
var hourOneDigit24Hours_Int: Int {
    return Int(self.hourOneDigit24Hours)!
}
var hourTwoDigit24Hours_Int: Int {
    return Int(self.hourTwoDigit24Hours)!
}
var hourOneDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h"
    return dateFormatter.string(from: self as Date)
}
var hourTwoDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh"
    return dateFormatter.string(from: self as Date)
}
var hourOneDigit24Hours: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "H"
    return dateFormatter.string(from: self as Date)
}
var hourTwoDigit24Hours: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH"
    return dateFormatter.string(from: self as Date)
}

// MARK:- MINUTE

var minuteOneDigit_Int: Int {
    return Int(self.minuteOneDigit)!
}
var minuteTwoDigit_Int: Int {
    return Int(self.minuteTwoDigit)!
}

var minuteOneDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "m"
    return dateFormatter.string(from: self as Date)
}
var minuteTwoDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "mm"
    return dateFormatter.string(from: self as Date)
}


// MARK:- SECOND

var secondOneDigit_Int: Int {
    return Int(self.secondOneDigit)!
}
var secondTwoDigit_Int: Int {
    return Int(self.secondTwoDigit)!
}

var secondOneDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "s"
    return dateFormatter.string(from: self as Date)
}
var secondTwoDigit: String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "ss"
    return dateFormatter.string(from: self as Date)
}

}