日期處理

時間格式 yyyy-MM-dd HH:mm


 時間轉時間戳
  class func getTimeIntervalFromDateString(dateString: String) -> TimeInterval {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        let timeZone = NSTimeZone(name: "Asia/Shanghai")
        dateFormatter.timeZone = timeZone as TimeZone!
      
        let date = dateFormatter.date(from: dateString)

        let timeInterval = date?.timeIntervalSince1970

        return timeInterval ?? 0
    }

    和當前時間比大小
    class func getTimeIntervalFromDateString(dateString: String, dateFormat: String) -> TimeInterval {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat
        let timeZone = NSTimeZone(name: "Asia/Shanghai")
        dateFormatter.timeZone = timeZone as TimeZone!
        
        
        let date = dateFormatter.date(from: dateString)
        
        let timeInterval = date?.timeIntervalSinceNow
        
        return timeInterval ?? 0
    }

距當前時間多久

class func getDMSStringFromTimeInterval(timeInterval: TimeInterval) -> String {
        //let remainingSeconds = timeInterval / 1000.0
        if timeInterval > -60 * 60 {
            return "\(Int(-timeInterval / 60))分鐘前"
        }
        if timeInterval > -24 * 60 * 60 {
            return "\(Int(-timeInterval / 3600))小時前"
        }
        return "\(Int(-timeInterval / 24 / 3600))天前"
    }

日歷部分 較亂


日歷展示用collectionView


lazy var contentCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        let cellW = ScreenW / 7
        flowLayout.itemSize = CGSize(width: cellW, height: cellW * 4 / 3)
        flowLayout.scrollDirection = .vertical
        flowLayout.headerReferenceSize = CGSize(width: ScreenW, height: 50)
        flowLayout.minimumInteritemSpacing = 0 //設置 y 間距
        flowLayout.minimumLineSpacing = 0 //設置 x 間距
        //UIEdgeInsetsMake(設置上下cell的上間距,設置cell左距離,設置上下cell的下間距,設置cell右距離);
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        //cell設置大小后,一行多少個cell,由cell的寬度決定
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenW, height: ScreenH), collectionViewLayout: flowLayout)
        collectionView.delegate = self

        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.white
        return collectionView
        
    }()

lazy var weekdays: NSArray = {
        let array = NSArray(objects: NSNull(), "0", "1", "2", "3", "4", "5", "6")
        return array
    }()

 lazy var newDate: Date = {
        let date = Date()
//        print(date)   2017-08-18 07:27:06 +0000
        return date
    }()

//日期組件
 lazy var comps: DateComponents = {
        let comps = DateComponents()
        return comps
    }()

    /// 日歷對象
    lazy var calender: NSCalendar = {
        let calender = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
        return calender!
    }()


/**
     *  獲取第N個月的時間
     *
     *  @param currentDate 當前時間
     *  @param index 第幾個月 正數(shù)為前  負數(shù)為后
     *
     *  @return @“2016年3月”
     */
    
    func getWantedDate(currentDate: Date, index: NSInteger) -> NSArray {
        
        let getDate = self.getPriousorLaterDateFromDate(date: currentDate, month: index)
        let str = self.dateFormatter.string(from: getDate)
        return str.components(separatedBy: "-") as NSArray
    }

/**
     *  根據(jù)當前時間獲取前后時間
     *
     *  @param date  當前時間
     *  @param month 第幾個月 正數(shù)為前  負數(shù)為后
     *
     *  @return 獲得時間
     */
    func getPriousorLaterDateFromDate(date: Date, month: Int) -> Date {
        self.comps.month = month
//        print(self.comps)
//        print(self.calender)
        //追加日期并返回新日期    在date日期上追加NSDateComponents對象內(nèi)的時間
//這里每個section代表每個月份
        let mDate = self.calender.date(byAdding: self.comps, to: date, options: NSCalendar.Options(rawValue: 0))
//        print(mDate)
        return mDate!  
 //2017-08-18 07:27:06 +0000
//2017-09-18 07:27:06 +0000   這里返回的mDate 單純的為了增加月份

        
    }


    /**
     根據(jù)當前月獲取有多少天
     
     - parameter dayDate: 當天月
     
     - returns: 天數(shù)
     */
    func getNumberOfDays(dayDate: Date) -> NSInteger {
        let calendar = NSCalendar.current
        let range = calendar.range(of: .day, in: .month, for: dayDate)
        //day 在 month里的取值范圍  根據(jù)dayDate來定 (1-30 或者 1-31 或者  28. 29)
        return (range?.count)!
    }



/**
     根據(jù)時間獲取這個月第一天周幾
     - parameter date: 月份  2017-08-18 07:27:06 +0000
     - returns: 周幾
     */
    func getDayByMonth(date: Date) -> String {

        //獲取用戶當前時區(qū)的日歷
        let calendar = Calendar.current
//        calendar.firstWeekday = 2 //設定每周的第一天為周1
        //篩選出 年月來
        let components = calendar.dateComponents([.year, .month], from: date)
        //獲取用戶當前時區(qū)當前年月的第一天
        let beginDate = calendar.date(from: components)
  
        return self.getDayByDate(date: beginDate!)   //月初時間  每個月1號是周幾

    }

    /**
     根據(jù)時間獲取周幾
     - parameter date: 時間
     - returns: 周幾
     */
    func getDayByDate(date: Date) -> String {
        self.calender.timeZone = self.timeZone
        //獲取這個月第一天周幾   周日-1   周一-2 ....
        let theComponents = self.calender.components(.weekday, from: date)
        return self.weekdays.object(at: theComponents.weekday!) as! String
    }


extension ViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 5 //就顯示5個月的數(shù)據(jù)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let date = self.getPriousorLaterDateFromDate(date: self.newDate, month: section)

        let timerString = self.getDayByMonth(dateString: date)
        let p_0 = Int(timerString)              
//        print(self.getNumberOfDays(dataList))
// 每個月第一天   例如是周2,  p_0=2 在日歷上前面就還有上個月的兩天
        let p_1 = self.getNumberOfDays(dayDate: dateList) + p_0! 
        return p_1;

    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OrderChooseTimeCollectionViewCell.identifier, for: indexPath) as! OrderChooseTimeCollectionViewCell
        
        
        let date = self.getPriousorLaterDateFromDate(date: self.newDate, month: indexPath.section)
        let array = self.getWantedDate(currentDate: newDate, index: indexPath.section)     //每個月的時間數(shù)組 [2107, 08, 18]
        let p = indexPath.row - Int(self.getDayByMonth(date: date))! + 1   //0-4+1  = -3
        
        
        let str: String?
        
        if p < 10 {
            str = p > 0 ? "0\(p)" : "-0\(-p)"
        }else {
            str = "\(p)"
        }
        
        let list = NSArray(objects: array[0], array[1], str!)
        var selectCount: Int?
        
        if self.selectedDate.count > 0 {
            selectCount = Int(self.selectedDate.componentsJoined(by: ""))
        }else {
            selectCount = 0
        }
        cell.updateDay(number: list, checkinDate: self.checkinDateArray, select: selectCount!, currentDate: self.getWantedDate(currentDate: newDate, index: 0))
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if kind == UICollectionElementKindSectionHeader {
            let headerCell = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: OrderSelectTimeCollectionReusableView.identifier, for: indexPath) as! OrderSelectTimeCollectionReusableView
            
            headerCell.updateTimer(array: self.getWantedDate(currentDate: self.newDate, index: indexPath.section))
            return headerCell
        }else {
            return UICollectionReusableView()
        }
    }
}



補充


// 
 先定義一個遵循某個歷法的日歷對象

NSCalendar
 *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

// 
 通過已定義的日歷對象,獲取某個時間點的NSDateComponents表示,并設置需要表示哪些信息(NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit等)

NSDateComponents
 *dateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit
 fromDate:[NSDate date]];

NSLog(@"year(年份):
 %i",
 dateComponents.year);

NSLog(@"quarter(季度):%i",
 dateComponents.quarter);

NSLog(@"month(月份):%i",
 dateComponents.month);

NSLog(@"day(日期):%i",
 dateComponents.day);

NSLog(@"hour(小時):%i",
 dateComponents.hour);

NSLog(@"minute(分鐘):%i",
 dateComponents.minute);

NSLog(@"second(秒):%i",
 dateComponents.second);

 

// 
 Sunday:1, Monday:2, Tuesday:3, Wednesday:4, Friday:5, Saturday:6

NSLog(@"weekday(星期):%i",
 dateComponents.weekday);

 

// 
 蘋果官方不推薦使用week

NSLog(@"week(該年第幾周):%i",
 dateComponents.week);

NSLog(@"weekOfYear(該年第幾周):%i",
 dateComponents.weekOfYear);

NSLog(@"weekOfMonth(該月第幾周):%i",
 dateComponents.weekOfMonth);

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容