NSDate of yesterday

后端 未结 6 1454
孤独总比滥情好
孤独总比滥情好 2020-11-30 01:59

How do I create an NSDate object with a custom date other than the current date? For example I would like to create a var of yesterday or of 2 days ago.

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 02:12

    The Rob's answer works great. If you are heavily using that kind of calculations you can even encapsulate that logic and make your own custom extensions and wrappers.

    That said i will suggest to take a look too at this fantastic library called SwiftDate. Even if you aren't using it, the README worth reading. It introduces the definition or Region that can be super useful for some scenarios and some handy initializers.

    Some cool stuffs and samples:

    • Math operation with dates: (1.years - 2.hours + 16.minutes).fromNow()
    • Composing time components: let dateInUTC = (2015.years | 12.months | 25.days | 20.hours | 10.minutes).inUTCRegion
    • Classy: let date = 5.days.fromNow, let date = 4.hours.ago
    • With Regions: let date = (6.hours + 2.minutes).fromNow(region: inRome)
    • And a lot more ...

    Hope it helps.

提交回复
热议问题