Make a new NSDate by combining two NSDates

前端 未结 5 1748
故里飘歌
故里飘歌 2021-02-15 11:11

I have NSDate* day1 and NSDate* day2. How can I make a NSDate* day3 by copying only year/month/day from day1 and hour/minute/second from d

5条回答
  •  温柔的废话
    2021-02-15 11:39

    Update Swift 4 & 4.1

     func combineDateAndTimeToOneDateForAPI() {
    
        let datefrmter = DateFormatter()
        datefrmter.dateFormat = "dd/MM/yyyy"
        let dateFromString = datefrmter.date(from: lblDate.text!)
    
        datefrmter.dateFormat = "h:mm a"
        let timeFromString = datefrmter.date(from: lblTime.text!)
    
        let calendar = NSCalendar.current
    
        let componentsOne = calendar.dateComponents([.year,.month,.day], from: dateFromString!)
        let componentsTwo = calendar.dateComponents([.hour,.minute,.second,.nanosecond], from: timeFromString!)
    
        let totalComponents = NSDateComponents()
        totalComponents.year = componentsOne.year!
        totalComponents.month = componentsOne.month!
        totalComponents.day = componentsOne.day!
        totalComponents.hour = componentsTwo.hour!
        totalComponents.minute = componentsTwo.minute!
        totalComponents.second = componentsTwo.second!
        totalComponents.nanosecond = componentsTwo.nanosecond!
    
        let finalDate = calendar.date(from: totalComponents as DateComponents)
        print(finalDate)
    
    }
    

提交回复
热议问题