Swift獲取今天婿牍,昨天侈贷,本周,上周等脂,本月俏蛮,上月的對應(yīng)日期。

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

直接上代碼了。

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

// MARK: 獲取當(dāng)前時間
// 這里的 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)前時間的前一天(后一天)

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

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

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

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

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

    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
      // 獲取幾天是幾號
      let day = comp.day
        
      // 計算當(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)前日期(去掉時分秒)基礎(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;
  }

以上代碼對應(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];
    // 獲取幾天是幾號
    NSInteger day = [comp day];
    
    // 計算當(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)前日期(去掉時分秒)基礎(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 為傳入需要計算的日期
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. 獲取上一周的日期和獲取上一個月的日期

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末单默,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子忘瓦,更是在濱河造成了極大的恐慌搁廓,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異枚抵,居然都是意外死亡线欲,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進(jìn)店門汽摹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來李丰,“玉大人,你說我怎么就攤上這事逼泣∨棵冢” “怎么了?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵拉庶,是天一觀的道長嗜憔。 經(jīng)常有香客問我,道長氏仗,這世上最難降的妖魔是什么吉捶? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮皆尔,結(jié)果婚禮上呐舔,老公的妹妹穿的比我還像新娘。我一直安慰自己慷蠕,他們只是感情好珊拼,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著流炕,像睡著了一般澎现。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上每辟,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天剑辫,我揣著相機(jī)與錄音,去河邊找鬼渠欺。 笑死妹蔽,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的峻堰。 我是一名探鬼主播,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼盅视,長吁一口氣:“原來是場噩夢啊……” “哼捐名!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起闹击,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤镶蹋,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體贺归,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡淆两,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了拂酣。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片秋冰。...
    茶點(diǎn)故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖婶熬,靈堂內(nèi)的尸體忽然破棺而出剑勾,到底是詐尸還是另有隱情,我是刑警寧澤赵颅,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布虽另,位于F島的核電站,受9級特大地震影響饺谬,放射性物質(zhì)發(fā)生泄漏捂刺。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一募寨、第九天 我趴在偏房一處隱蔽的房頂上張望族展。 院中可真熱鬧,春花似錦绪商、人聲如沸苛谷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽腹殿。三九已至,卻和暖如春例书,著一層夾襖步出監(jiān)牢的瞬間锣尉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工决采, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留自沧,地道東北人。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓树瞭,卻偏偏與公主長得像拇厢,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子晒喷,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,573評論 2 359

推薦閱讀更多精彩內(nèi)容