如何在Swift中获取两个日期之间的天数?

编程入门 行业动态 更新时间:2024-10-25 22:26:42
本文介绍了如何在Swift中获取两个日期之间的天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请考虑我们具有以下函数签名:

Consider that we have a function signature as:

func datesRange(from: Date, to: Date) -> [Date]

应从开始使用和至日期实例,并返回一个数组,其中包含其参数之间的日期(天)。

which should take from date and to date instances and returns an array containing the dates (days) between its parameters. How to achieve it?

推荐答案

您可以这样实现:

func datesRange(from: Date, to: Date) -> [Date] { // in case of the "from" date is more than "to" date, // it should returns an empty array: if from > to { return [Date]() } var tempDate = from var array = [tempDate] while tempDate < to { tempDate = Calendar.current.date(byAdding: .day, value: 1, to: tempDate)! array.append(tempDate) } return array }

用法:

let today = Date() let nextFiveDays = Calendar.current.date(byAdding: .day, value: 5, to: today)! let myRange = datesRange(from: today, to: nextFiveDays) print(myRange) /* [2018-03-20 14:46:03 +0000, 2018-03-21 14:46:03 +0000, 2018-03-22 14:46:03 +0000, 2018-03-23 14:46:03 +0000, 2018-03-24 14:46:03 +0000, 2018-03-25 14:46:03 +0000] */

更多推荐

如何在Swift中获取两个日期之间的天数?

本文发布于:2023-10-25 18:30:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527747.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:天数   两个   日期   如何在   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!