iOS-字符串日期格式转换的三种方式

57 篇文章 1 订阅

现实开发中,可能会遇到字符串格式的日期,比如后台返回{date : "2017-12-08 13:28:59",...},我们需要对字符串进行截取使用

需求1:获取年月日
需求2:更换年月日的顺序,比月/日/年


关于日期,首先介绍下:DateFormatter

苹果官方文档:Date Formatters

其中写到:

“Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable.”

也就是说,创建DateFormatter的过程开销很大!如果使用formatter比较频繁的话,建议使用时保持一个单例,而不是每次去重新创建DateFormatter对象。

所以在项目中如果多处用到 DateFormatter,要不用单例来实现格式化,要不就少用 DateFormatter,用其他方式代替。


对于需求1:获取年月日

  • 方法一:通过 DateFormatter 格式化成Date类型,再改变formatter.dateFormat的属性将 Date 转成需求的字符串
  • 方法二:通过字符串截取来实现
  • 方法三:通过字符串的分组(components)来实现
  • 方法四:通过正则表达式(RegularExpression)来匹配

对于需求2:更换年月日的顺序

  • 方法一:通过 DateFormatter 格式化成Date类型,再改变formatter.dateFormat的属性将 Date 转成需求的字符串
  • 方法二:通过字符串的截取或者字符串的分组(components)来实现
  • 方法三:通过正则表达式(RegularExpression)来匹配

代码示例:
需求1
方法一:
let dateString = "2017-12-08 13:28:59"
// 初始化 DateFormatter
let dateFormatter = DateFormatter()
// 设置 dateFormat 格式
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
// 字符串 转 Date
guard let date = dateFormatter.date(from: dateString) else { return }
// 设置需求所需的 dateFormat 格式
dateFormatter.dateFormat = "yyyy-MM-dd"
// Date 转 字符串
let newDateString = dateFormatter.string(from: date)
// 输出
print(newDateString) // 2017-12-08

方法二:
let dateString = "2017-12-08 13:28:59"
// 计算目标 index
let index = dateString.index(dateString.startIndex, offsetBy: 10)
// 字符串截取
let substring = dateString[..<index]
// 输出
print(substring) // 2017-12-08

方法三:
let dateString = "2017-12-08 13:28:59"
// 通过空格分割字符串
let result = dateString.components(separatedBy: " ")
// 获取第一个,就是需求所需字符串
let nDateString = result[0]
// 输出
print(nDateString) // 2017-12-08

方法四:
let dateString = "2017-12-08 13:28:59"
// 设置正则模型
let formatPattern = "^(\\d{4})-(\\d{2})-(\\d{2}).*"
// 通过正则查找并修改格式
let formatedDate = dateString.replacingOccurrences(of: formatPattern, with: "$1-$2-$3", options: .regularExpression)
// 输出
print(formatedDate) // 2017-12-08


需求2
方法一:
let dateString = "2017-12-08 13:28:59"

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

guard let date = dateFormatter.date(from: dateString) else { return }
// 修改需要所需格式
dateFormatter.dateFormat = "MM/dd/yyyy"

let newDateString = dateFormatter.string(from: date)

print(newDateString) // 12/08/2017

方法二:
let dateString = "2017-12-08 13:28:59"
通过空格分割获取知道日期字符串
let result1 = dateString.components(separatedBy: " ")
// 取出年月日字符串
let nDateString1 = result1[0]
// 通过“-”号分割日期
let result2 = nDateString1.components(separatedBy: "-")
// 更换日期顺序和样式
let nDateString2 = result2[1] + "/" + result2[2] + "/" + result2[0]
// 输出
print(nDateString2) // 12/08/2017

方法三:
let dateString = "2017-12-08 13:28:59"
// 正则模型:^\d{4}表示前四为为数字,.*为任意字符
let formatPattern = "^(\\d{4})-(\\d{2})-(\\d{2}).*"
// 通过正则查找并修改格式
let formatedDate = dateString.replacingOccurrences(of: formatPattern, with: "$2/$3/$1", options: .regularExpression)
// 输出
print(formatedDate) // 12/08/2017

几种方式的比较
  • 为了减少内存开销,减少使用 DateFormatter

  • 对于简单的日期字符串格式化,字符串的截取或者字符串的分组即可实现。复杂的就麻烦了

  • 对于较复杂的日期字符串格式化,使用正则表达式就能看见它的好处了。简单的更简单
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS移动端,时间格式为yyyy-MM-dd时计算其毫秒值会返回NaN的问题可以通过将时间格式为yyyy/MM/dd来解决。具体做法是使用.replace()函数将日期字符串中的"-"替换为"/",然后再将换后的日期字符串通过new Date()获取其毫秒值。例如,可以将日期字符串'2021-05-20 18:00:00'换为'2021/05/20 18:00:00',然后再使用new Date('2021/05/20 18:00:00').getTime()来获取其毫秒值。 另外,还有一种解决方法是将日期格式设置为format="yyyy/MM/dd HH:mm:ss",避免使用format="yyyy-MM-dd HH:mm:ss"的格式,因为在iOS上使用后者的格式会导致返回NaN的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [解决IOS移动端 格式为yyyy-MM-dd时计算其毫秒值会返回NaN](https://blog.csdn.net/qq_44806249/article/details/124802374)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [【IOS】时间格式 NaN 问题解决](https://blog.csdn.net/weixin_43900414/article/details/130523881)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [java后台解析苹果的P12安装证书类封装](https://download.csdn.net/download/qq_42684707/88279835)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值