Swift 3 Easy way to truncate Date to start of the day/month/year

后端 未结 2 2141
挽巷
挽巷 2021-02-19 22:39

Is there any easy way to truncate date like we can do in Oracle Database? For example, I need to set value starting from midnight. In Oracle I can do TRUNC(SYSDATE). But I canno

2条回答
  •  猫巷女王i
    2021-02-19 23:24

    Note the +0000 at the end of the time in your sample.

    The start of the day where? I updated the sample to show what you want.

    var comp: DateComponents = Calendar.current.dateComponents([.year, .month, .day], from: Date())
    comp.timeZone = TimeZone(abbreviation: "UTC")!
    let truncated = Calendar.current.date(from: comp)!
    print(truncated)
    

    It prints 2017-06-14 00:00:00 +0000. Again, note the +0000 at the end.

    By default the timezone is set to be the current timezone and the hour, minute, and second are 0 in that timezone.


    I will assume that you want the current timezone. With that stipulation, your code is correct.

提交回复
热议问题