// // ZFDateTool.swift // MyStudyDemo // // Created by FranZhou on 16/6/12. // Copyright © 2016年 kimree. All rights reserved. // import UIKit public class ZFDateTool: NSObject { // dateformat default = "yyyy-MM-dd" public static var formatString: String! = "yyyy-MM-dd"{ willSet{ self.dateFormatter.dateFormat = newValue } } private static let dateFormatter: NSDateFormatter = { let dateFormat = NSDateFormatter() dateFormat.dateFormat = ZFDateTool.formatString return dateFormat }() // MARK: - 获得字符串时间 public class func dateFromString(dateString: String, formatString:String = ZFDateTool.formatString) -> NSDate?{ var dateFormat = ZFDateTool.dateFormatter if formatString != ZFDateTool.formatString{ dateFormat = dateFormat.copy() as! NSDateFormatter dateFormat.dateFormat = formatString } return dateFormat.dateFromString(dateString) } // MARK: - 获取时间字符串 public class func stringFromDate(date: NSDate = NSDate(), formatString:String = ZFDateTool.formatString) -> String{ var dateFormat = ZFDateTool.dateFormatter if formatString != ZFDateTool.formatString{ dateFormat = dateFormatter.copy() as! NSDateFormatter dateFormat.dateFormat = formatString } return dateFormat.stringFromDate(date) } // MARK: - timestamp 基于秒 public class func timestamp(date: NSDate = NSDate()) -> Double{ let timestamp = date.timeIntervalSince1970 return timestamp } public class func dateFromTimestamp(timestamp: Double) -> NSDate{ let date = NSDate(timeIntervalSince1970: timestamp) return date } // MARK: - 获取 年 月 日 星期 private static let calendar: NSCalendar = { let calendar = NSCalendar.currentCalendar() // 设定每周的第一天从星期几开始,比如: // 如需设定从星期日开始,则firstWeekday传入1 // 如需设定从星期一开始,则firstWeekday传入2 // 该设置只影响 NSCalendar 不会影响到 NSDateComponents 的处理方式 calendar.firstWeekday = 2 return calendar }() public class func yearWithDate(date: NSDate = NSDate()) -> Int{ let components = calendar.components(NSCalendarUnit.Year, fromDate: date) return components.year } public class func monthWithDate(date: NSDate = NSDate()) -> Int{ let month = calendar.ordinalityOfUnit(NSCalendarUnit.Month, inUnit: NSCalendarUnit.Year, forDate: date) return month } public class func dayWithDate(date: NSDate = NSDate()) -> Int{ let day = calendar.ordinalityOfUnit(NSCalendarUnit.Day, inUnit: NSCalendarUnit.Month, forDate: date) return day } public class func weekdayWithDate(date: NSDate = NSDate()) -> Int{ // calendar.components(NSCalendarUnit.Weekday, fromDate: date) 该方法获取的weekday永远都是 1 星期天 2 星期一 .... 这种顺序 // 如果想获得 firstWeekday 进行处理后的正确星期时间, 用下述方法 let weekday = calendar.ordinalityOfUnit(NSCalendarUnit.Weekday, inUnit: NSCalendarUnit.WeekOfYear, forDate: date) return weekday } }
时间: 2024-10-27 05:37:48