时间格式 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);