Swift獲取今天,昨天,本周,上周,本月,上月的對(duì)應(yīng)日期。

項(xiàng)目需求用到,以下代碼有部分是根據(jù)iOS修改而來。

直接上代碼了。

1. 獲取當(dāng)前時(shí)間

// MARK: 獲取當(dāng)前時(shí)間
// 這里的 type 是指日期的格式 “yyyyMMdd” 或者 “yyyy-MM-dd” 這樣子
class func nowTime(_ type: String?) -> String {
        let currentDate = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = type ?? "yyyyMMdd"
        let time = formatter.string(from: currentDate)
        return time
    }

2. 獲取當(dāng)前時(shí)間的前一天(后一天)

這個(gè)方法可以用來獲取相對(duì)與今天的任意一天時(shí)間
// MARK: 前一天的時(shí)間
// nowDay 是傳入的需要計(jì)算的日期
class func getLastDay(_ nowDay: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyyMMdd"
        
        // 先把傳入的時(shí)間轉(zhuǎn)為 date
        let date = dateFormatter.date(from: nowDay)
        let lastTime: TimeInterval = -(24*60*60) // 往前減去一天的秒數(shù),昨天
//        let nextTime: TimeInterval = 24*60*60 // 這是后一天的時(shí)間,明天
        
        let lastDate = date?.addingTimeInterval(lastTime)
        let lastDay = dateFormatter.string(from: lastDate!)
        return lastDay
    }      

以上代碼對(duì)應(yīng)的iOS代碼是:

// 得到以前的某個(gè)日期
- (NSString *)getAgoTime:(NSString *)second
{
    //得到當(dāng)前的時(shí)間
    NSDate * date = [NSDate date];

    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    //設(shè)置時(shí)間間隔(秒)(這個(gè)我是計(jì)算出來的,不知道有沒有簡(jiǎn)便的方法 )
    NSTimeInterval time = [second intValue];//一年的秒數(shù)
    //得到一年之前的當(dāng)前時(shí)間(-:表示向前的時(shí)間間隔(即去年),如果沒有,則表示向后的時(shí)間間隔(即明年))

    NSDate * lastYear = [date dateByAddingTimeInterval:-time];

    //轉(zhuǎn)化為字符串
    NSString * startDate = [dateFormatter stringFromDate:lastYear];
    return startDate;
}

3. 獲取某一天所在周一和周日的日期

// MARK: 獲取某一天所在的周一和周日
class func getWeekTime(_ dateStr: String) -> Array<String> {
      let dateFormatter = DateFormatter()
      dateFormatter.dateFormat = "yyyyMMdd"
      let nowDate = dateFormatter.date(from: dateStr)
      let calendar = Calendar.current
      let comp = calendar.dateComponents([.year, .month, .day, .weekday], from: nowDate!)
        
      // 獲取今天是周幾
      let weekDay = comp.weekday
      // 獲取幾天是幾號(hào)
      let day = comp.day
        
      // 計(jì)算當(dāng)前日期和本周的星期一和星期天相差天數(shù)
      var firstDiff: Int
      var lastDiff: Int
      // weekDay = 1;
      if (weekDay == 1) {
          firstDiff = -6;
          lastDiff = 0;
      } else {
          firstDiff = calendar.firstWeekday - weekDay! + 1
          lastDiff = 8 - weekDay!
      }
       
      // 在當(dāng)前日期(去掉時(shí)分秒)基礎(chǔ)上加上差的天數(shù)
      var firstDayComp = calendar.dateComponents([.year, .month, .day], from: nowDate!)
      firstDayComp.day = day! + firstDiff
      let firstDayOfWeek = calendar.date(from: firstDayComp)
      var lastDayComp = calendar.dateComponents([.year, .month, .day], from: nowDate!)
      lastDayComp.day = day! + lastDiff
      let lastDayOfWeek = calendar.date(from: lastDayComp)
        
      let firstDay = dateFormatter.string(from: firstDayOfWeek!)
      let lastDay = dateFormatter.string(from: lastDayOfWeek!)
      let weekArr = [firstDay, lastDay]
        
      return weekArr;
  }

以上代碼對(duì)應(yīng)的iOS代碼是:

#pragma mark - 獲取某一天所在的周一和周日
+ (NSString *)getWeekTime:(NSString *)dateStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *nowDate = [formatter dateFromString:dateStr];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = nil;
    if (DEV_VER >= 8.0) {
        comp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitDay fromDate:nowDate];
    } else {
         comp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSDayCalendarUnit fromDate:nowDate];
    }
    
    // 獲取今天是周幾
    NSInteger weekDay = [comp weekday];
    // 獲取幾天是幾號(hào)
    NSInteger day = [comp day];
    
    // 計(jì)算當(dāng)前日期和本周的星期一和星期天相差天數(shù)
    long firstDiff,lastDiff;
    // weekDay = 1;
    if (weekDay == 1) {
        firstDiff = -6;
        lastDiff = 0;
    } else {
        firstDiff = [calendar firstWeekday] - weekDay + 1;
        lastDiff = 8 - weekDay;
    }
    
    // 在當(dāng)前日期(去掉時(shí)分秒)基礎(chǔ)上加上差的天數(shù)
    NSDateComponents *firstDayComp = nil;
    NSDateComponents *lastDayComp = nil;
    if (DEV_VER >= 8.0) {
        firstDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:nowDate];
    } else {
        firstDayComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit  fromDate:nowDate];
    }
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];
    if (DEV_VER >= 8.0) {
        lastDayComp = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay   fromDate:nowDate];
    } else {
        lastDayComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit   fromDate:nowDate];
    }
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek = [calendar dateFromComponents:lastDayComp];
    
    NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];
    NSString *lastDay = [formatter stringFromDate:lastDayOfWeek];
    NSString *weekStr = [NSString stringWithFormat:@"%@ 至 %@", firstDay, lastDay];
    
    return weekStr;
}

4. 獲取某一日所在月份的開始和結(jié)束日期

// MARK: 當(dāng)月開始日期
// nowDay 為傳入需要計(jì)算的日期
class func startOfCurrentMonth(_ nowDay: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyyMMdd"
        let nowDayDate = dateFormatter.date(from: nowDay)
        
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month], from: nowDayDate!)
        let startOfMonth = calendar.date(from: components)
        
        let day = dateFormatter.string(from: startOfMonth!)
        return day
    }
    
// MARK: 當(dāng)月結(jié)束日期
class func endOfCurrentMonth(_ nowDay: String, returnEndTime:Bool = false) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyyMMdd"
        let nowDayDate = dateFormatter.date(from: nowDay)
        
        let calendar = Calendar.current
        var components = DateComponents()
        components.month = 1
        if returnEndTime {
            components.second = -1
        } else {
            components.day = -1
        }
        //startOfCurrentMonth
        let currentMonth = calendar.dateComponents([.year, .month], from: nowDayDate!)
        let startOfMonth = calendar.date(from: currentMonth)
        let endOfMonth = calendar.date(byAdding: components, to: startOfMonth!)
        
        let day = dateFormatter.string(from: endOfMonth!)
        return day
    }      

5. 獲取上一周的日期和獲取上一個(gè)月的日期

當(dāng)然是先根據(jù)上述方法獲取本周(本月)的第一天,然后獲取前一天,也就是上周(上月)的最后一天,然后再去重新獲取那一周(那個(gè)月)的日期了。

以上所使用的格式都是 yyyyMMdd 的格式,在使用的過程中大家可以自己設(shè)置成需要的格式。 另外以上所有的 nowDay 都是你傳入的需要計(jì)算的那一天的日期格式,是 String 類型的。

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

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

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