简体   繁体   English

如何从日期字符串 Swift 中隐藏时间

[英]How to hide Time from date string Swift

I have the string:我有字符串:

1980-02-17T04:00:00.000Z 1980-02-17T04:00:00.000Z

I want to remove all text after "T" in:我想删除“T”之后的所有文本:

Text(user.DOB)

How would I do this?我该怎么做?

Thank you谢谢

Option 1 (formatting a date object):选项 1(格式化日期对象):

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYY-MM-dd"
let monthString = dateFormatter.string(from: user.DOB)

where:在哪里:

dateFormatter.dateFormat = "YYY-MM-dd"

represents the format of date you want代表你想要的日期格式

If you don't have a date object you can get one from your string:如果你没有日期 object 你可以从你的字符串中得到一个:

  formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

  let parsedDate = formatter.dateFromString(date)

Option 2(formating a date string):选项 2(格式化日期字符串):

let parsedDate = date.prefix(10) 

While not particularly sophisticated, you could simply go for虽然不是特别复杂,但您可以简单地使用 go

Text(user.DOB.prefix(10))

It lets you keep MongoDB's format for elsewhere in your app if you end up needing it.如果您最终需要它,它可以让您在应用程序的其他地方保留 MongoDB 的格式。

var str = "1980-02-17T04:00:00.000Z"
if let index = str.firstIndex(of: "T") {
    let a = str.substring(to: index)
    print(a) // Prints 1980-02-17
}

Considering you don't want T in the final output.考虑到您不想在最终的 output 中出现 T。

Or you could just:或者你可以:

var dateStringWithoutT = "1980-02-17T04:00:00.000Z"
                              .split(separator: "T")
                              .first

What the above code does is, split the string by "T" and you get ["1980-02-17","04:00:00.000Z"] , then, use array's first property to get what you need.上面的代码所做的是,将字符串除以 "T" 并得到["1980-02-17","04:00:00.000Z"] ,然后使用数组的first属性来获取所需的内容。

Complexity: O(n)复杂度:O(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM