I have the string:
1980-02-17T04:00:00.000Z
I want to remove all text after "T" in:
Text(user.DOB)
How would I do this?
Thank you
I have the string:
1980-02-17T04:00:00.000Z
I want to remove all text after "T" in:
Text(user.DOB)
How would I do this?
Thank you
Option 1 (formatting a date object):
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:
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let parsedDate = formatter.dateFromString(date)
Option 2(formating a date string):
let parsedDate = date.prefix(10)
While not particularly sophisticated, you could simply go for
Text(user.DOB.prefix(10))
It lets you keep MongoDB's format for elsewhere in your app if you end up needing it.
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.
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.
Complexity: O(n)