0

I try to convert the Date to a string and then trim it. Somehow Xcode doesnt accept beforeConvas a String. I am clueless, also tried other methods to convert the date to a string, like formatter.sring(from: date) which did not work.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let date = Date()
let beforeConv = "\(date)"

let start = beforeConv(beforeConv.startIndex, offsetBy: 11) // Cannot call value of non-function type 'String'
let end = beforeConv(beforeConv.endIndex, offsetBy: -12)    // Cannot call value of non-function type 'String'
let range = start..<end
let cleanTime = beforeConv[range]
let postZone = String(cleanTime)
New Dev
  • 48,427
  • 12
  • 87
  • 129
Jan Swoboda
  • 152
  • 2
  • 15
  • I think what you wanted to do was `beforeConv.index(..., offsetBy: 11)` to avoid the error. But what do you mean by converting, then trimming? Are you trying to print out the day part of the date? Then, there's definitely a better way. What are you actually trying to accomplish? – New Dev Jun 24 '20 at 00:03
  • @New Dev Trying to get the Day part and then converting to an Int, to calculate with it – Jan Swoboda Jun 24 '20 at 00:05
  • Look for how to convert a date to a datecomponent. Example: https://stackoverflow.com/questions/38248941/how-to-get-time-hour-minute-second-in-swift-3-using-nsdate – New Dev Jun 24 '20 at 00:12

1 Answers1

1

It's pretty hacky (and needless) to convert a Date to a String in order to extract the day component. Luckily, Swift offers a DateComponents to do work with components that comprise a date. Here's how it works:

let date = Date()

let dateParts = Calendar.current.dateComponents([.day, .month], from: date)

let day = dateParts.day // this is an optional Int?
let month = dateParts.month

For a single component, you can also do:

// this is Int
let day = Calendar.current.component(.day, from: date) 
New Dev
  • 48,427
  • 12
  • 87
  • 129