0

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

AnderCover
  • 2,488
  • 3
  • 23
  • 42

4 Answers4

4

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) 
1

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.

JarWarren
  • 1,343
  • 2
  • 13
  • 18
  • I would assume that's already been considered by MongoDB when it produced the string. The question only asked how to remove a portion of the String. – JarWarren May 13 '21 at 23:19
  • 2
    From the UX perspective, this is a totally wrong answer. – Alexander May 14 '21 at 02:32
  • @Alexander it’s the exact answer he asked for – JarWarren May 14 '21 at 03:17
  • 2
    That's why I said "From the UX perspective...". Your answer to OP's question is correct in a narrow sense, but OP is asking the wrong question, and you're accidentally further guiding him down his wrong direction by not letting him know that passing an ISO 8601 formatted string to a `Text` is really suspitious – Alexander May 14 '21 at 03:32
1
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.

learner
  • 51
  • 1
  • 6
0

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)

dvlprliu
  • 24
  • 2