John Doodle John Doodle -4 years ago 191
Swift Question

Check if a String is the current date

I am new to swift and I would like to separate a string into an array. In my case the string is "20170227" and I would like to have it in an array like [2017,02,27]. I have tried doing this, but the code was way too long and I think by far to complicated for what it is.

var date = "20170227"
var Space: Character = " "
let indexMain = date.index(date.startIndex, offsetBy: 4)
date.insert(Space, at: indexMain)

which eventually only returns 2017 0227, so I'm lost... Thanks in advance!

Answer Source

From your comment if you want to check that date of string is current date than you can use DateFormatter to convert string to date and then use isDateInToday to check date is today date.

var dateString = "20170227"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMdd"
if let date = dateString), Calendar.current.isDateInToday(date) {
     print("String date is today's date")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download