ios - Swift - 获取下一个日期

标签 ios swift xcode

我正在尝试编写一个函数,它接受一个字符串(格式为“dd MM yyyy”)并返回作为参数给出的日期之后的日期。

例如:

let nextDay = getNextDay("31 12 2016")
print(nextDay)

将打印:

01 01 2017

谁能告诉我怎么做?谢谢

最佳答案

下面是可能对您有所帮助的代码片段。

//Call method like this

convertNextDate(dateString: "31 12 2016")


// Method is here

func convertNextDate(dateString : String){    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MM yyyy"
    let myDate = dateFormatter.date(from: dateString)!
    let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
    let somedateString = dateFormatter.string(from: tomorrow!)
    print("your next Date is \(somedateString)")
}

另一种方法是创建扩展,这就是它。

extension String {
    func convertToNextDate(dateFormat: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat
        let myDate = dateFormatter.date(from: self)!
        let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
        return dateFormatter.string(from: tomorrow!)
    }
}

用法

print("31 12 2016".convertToNextDate(dateFormat: "dd MM yyyy"))

注意:您可以使用所需的日期格式,只要确保它是合适的即可。

关于ios - Swift - 获取下一个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490848/

相关文章:

ios - camera.getPicture 在选择图库中的 cordova ios 中滞后了太多时间

ios - 如何在 Swift 项目中实现 PayU Objective C 库

ios - 远程通知字符串的本地化会破坏设备设置语言和区域设置 Swift

运行 flutter 升级后iOS模拟器性能不佳

ios - 如何在 Xcode 9 中在 iOS 设备上运行我的应用程序?

ios - 如何从 Swift 访问 UIColor 的宏

ios - UICOllectionview,滚动到标题中包含 NSString 的第一个单元格

ios - 每个 CollectionView Cell 都有独特的计时器

iOS tableview 在 UiBuilder 中显示为空

xcode 8.3 错误 : The specified item could not be found in the keychain