日期处理

时间格式 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 第几个月 正数为前  负数为后
     *
     *  @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
    }

/**
     *  根据当前时间获取前后时间
     *
     *  @param date  当前时间
     *  @param month 第几个月 正数为前  负数为后
     *
     *  @return 获得时间
     */
    func getPriousorLaterDateFromDate(date: Date, month: Int) -> Date {
        self.comps.month = month
//        print(self.comps)
//        print(self.calender)
        //追加日期并返回新日期    在date日期上追加NSDateComponents对象内的时间
//这里每个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 单纯的为了增加月份

        
    }


    /**
     根据当前月获取有多少天
     
     - parameter dayDate: 当天月
     
     - returns: 天数
     */
    func getNumberOfDays(dayDate: Date) -> NSInteger {
        let calendar = NSCalendar.current
        let range = calendar.range(of: .day, in: .month, for: dayDate)
        //day 在 month里的取值范围  根据dayDate来定 (1-30 或者 1-31 或者  28. 29)
        return (range?.count)!
    }



/**
     根据时间获取这个月第一天周几
     - parameter date: 月份  2017-08-18 07:27:06 +0000
     - returns: 周几
     */
    func getDayByMonth(date: Date) -> String {

        //获取用户当前时区的日历
        let calendar = Calendar.current
//        calendar.firstWeekday = 2 //设定每周的第一天为周1
        //筛选出 年月来
        let components = calendar.dateComponents([.year, .month], from: date)
        //获取用户当前时区当前年月的第一天
        let beginDate = calendar.date(from: components)
  
        return self.getDayByDate(date: beginDate!)   //月初时间  每个月1号是周几

    }

    /**
     根据时间获取周几
     - 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个月的数据
    }
    
    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)     //每个月的时间数组 [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);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336

推荐阅读更多精彩内容