【问题标题】:add days onto string date swift将日期添加到字符串日期 swift
【发布时间】:2018-05-16 21:50:05
【问题描述】:

我有各种字符串格式的日期,保存在字典中。我想检索这些日期并在其上添加一两天,具体取决于其他条件。

是否需要将字符串日期转换为 NSDate、提取组件(年、月、日)、编辑组件(添加一两天)并将新组件重新组合到 NSDate/String 中?

例如,我的字典“26/05/2018”中有一个字符串日期,我想添加一天,我想生成一个新字符串“27/05/2018”。

谢谢

【问题讨论】:

  • 作为一般建议 - 是的
  • 您的日期不应包含任何字符串。尽快将它们全部转换为Date。您应该将其转换为字符串的唯一时间是将其显示给用户。
  • 为什么需要在字典中存储字符串?为什么不存储日期并根据需要对其进行格式化?
  • 不,您不需要处理将日期拆分为组件的问题。使用date(byAdding:value:to:wrappingComponents:) 增加日期。

标签: ios swift nsdate


【解决方案1】:
  1. 使用适当的 DateFormatter 将字符串转换为日期
  2. 添加组件以获取新日期
  3. 返回日期

【讨论】:

    【解决方案2】:

    你可以这样开始:

    extension String {
    
        func toDate(format: String) -> Date? {
    
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = format
            dateFormatter.locale = Locale.current
            return dateFormatter.date(from: self)
        }
    }
    
    extension Date {
    
        func toString(format: String) -> String? {
    
            let df = DateFormatter()
            df.dateFormat = format
            return df.string(from: self)
        }
    
        func add(component: Calendar.Component, value: Int) -> Date? {
    
            return Calendar.current.date(byAdding: component, value: value, to: self)
        }
    }
    

    【讨论】:

    • 为什么要在代码中硬编码公历?只需使用Calendar.current
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多