一种返回两个日期之间的日期数组的方法

编程入门 行业动态 更新时间:2024-10-23 18:35:43
本文介绍了一种返回两个日期之间的日期数组的方法-Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试获取一个对象的时间戳与未来30天之间的日期数组。

I'm trying to get an array of dates between the time stamp of one of my objects and 30 days into the future.

我使用了下面的代码,但是我没有得到想要的结果,并且在尝试创建标题中描述的方法时遇到了麻烦。任何帮助都会很棒,谢谢。

I've used the code below but i'm not getting the desired result and am having trouble trying to make a method described in the title. Any help would be great, thank you.

var dates = [Date]() func fetchDays() { let cal = Calendar.current var dateComponents = DateComponents() dateComponents.year = 2017 dateComponents.month = 2 dateComponents.day = 12 guard let startDate = cal.date(from: dateComponents) else { return } var start = cal.startOfDay(for: startDate) for _ in 0 ... 30 { guard let daysBetween = cal.date(byAdding: .day, value: 1, to: startDate) else { return } start = daysBetween dates.append(start) } }

推荐答案

您将1加上相同的开始日期,因此您的数组将一遍又一遍地填充相同的日期。只需将 1 替换为循环索引+ 1。

You are adding 1 to the same start date so your array is filled with the same date over and over. Simply replace 1 with the loop index + 1.

for i in 0 ... 30 { if let newDate = cal.date(byAdding: .day, value: i + 1, to: startDate) { dates.append(newDate) } }

您不需要开始变量。

更多推荐

一种返回两个日期之间的日期数组的方法

本文发布于:2023-05-28 06:53:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/315084.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file 'D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

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

>www.elefans.com

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