Ian Thompson
Ian Thompson

Reputation: 51

How can I display text on a certain date using Swift?

I am currently trying to display a string on a certain date (Halloween). I have pasted the code I used below:

 var dateComponents = NSDateComponents()
    var calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
    var currentDate = NSDate()
    var halloweenDate = calendar?.dateFromComponents(dateComponents)
    dateComponents.day = 1 
    // I used 1 as the day only for testing
    dateComponents.month = 10 
    dateComponents.year = 2015

I then created this If statement to see if the current date is equal to halloweenDate.

    if currentDate == halloweenDate {
        println("Happy Halloween!") 

    }

I know that the println() does not display text on the screen, I am just using it for testing

I am not sure what I am doing wrong or leaving out.

This is what I have so far. As a fairly new programmer, this looks like it would work, but as I have found, if it seems easy, It probably wrong

Thanks.

Upvotes: 0

Views: 267

Answers (4)

Joey deVilla
Joey deVilla

Reputation: 8473

You want to get the month and day components of the current date and compare them to 10 and 31, respectively, like this:

// This is in Swift 2
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let now = NSDate()
let nowComponents = calendar.components([.Month, .Day], fromDate: now)
if nowComponents.month == 10 && nowComponents.day == 31 {
  print("Happy Halloween!")
}

Upvotes: 0

Duncan C
Duncan C

Reputation: 131481

Welcome to SO. Your question is kind of vague.

If your app happens to be launched/brought to the foreground on the date in question then you could use some date math to recognized the fact and display an alert.

If your app is not run then your best bet is to post a local notification with a fire date on your target date. Then when the date rolls around the system will display a message to the user and if the user taps on it, your app will be launched.

Both approaches above take some setup.

Can you clarify what it is you want to do?

Upvotes: 0

msalafia
msalafia

Reputation: 2743

Set the values of dateComponent just before callingdateFromComponent on halloweenDate.

Upvotes: 2

Ana
Ana

Reputation: 1

Please use NSDateFormatter. For example :

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"

var strDate = "01/10/2015"
var currentDate = dateFormatter.dateFromString(strDate)

It'll works fine for you.

Upvotes: -1

Related Questions