Skip to content

Instantly share code, notes, and snippets.

@scttymn
Created September 1, 2014 02:12
Show Gist options
  • Save scttymn/293f24cdb0ecb958234c to your computer and use it in GitHub Desktop.
Save scttymn/293f24cdb0ecb958234c to your computer and use it in GitHub Desktop.
Future Day Calculator
//
// ViewController.swift
// DaysUntilDate
//
// Created by Scotty Moon on 8/31/14.
// Copyright (c) 2014 Scotty Moon. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var monthTextField: UITextField!
@IBOutlet weak var dayTextField: UITextField!
@IBOutlet weak var yearTextField: UITextField!
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setDefaultValues()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func setDefaultValues() {
var calendar = NSCalendar(identifier: NSGregorianCalendar)
var currentDate = calendar.components(
NSCalendarUnit.CalendarUnitDay |
NSCalendarUnit.CalendarUnitMonth |
NSCalendarUnit.CalendarUnitYear,
fromDate: NSDate.date())
if monthTextField.text.isEmpty {
monthTextField.text = String(currentDate.month)
}
if dayTextField.text.isEmpty {
dayTextField.text = String(currentDate.day)
}
if yearTextField.text.isEmpty {
yearTextField.text = String(currentDate.year)
}
resultLabel.text = ""
}
@IBAction func calculateFutureDays(sender: AnyObject) {
setDefaultValues()
var futureDateComponents = NSDateComponents()
futureDateComponents.day = dayTextField.text.toInt()!
futureDateComponents.month = monthTextField.text.toInt()!
futureDateComponents.year = yearTextField.text.toInt()!
var calendar = NSCalendar(identifier: NSGregorianCalendar)
var futureDate = calendar.dateFromComponents(futureDateComponents)
var currentDate = NSDate.date()
var durationDateComponents = calendar.components(NSCalendarUnit.CalendarUnitDay,
fromDate: currentDate,
toDate: futureDate!,
options: nil)
var numberOfDaysUntilFutureDate = durationDateComponents.day
var numberFormatter = NSNumberFormatter()
numberFormatter.usesGroupingSeparator = true
var dayString = numberFormatter.stringFromNumber(numberOfDaysUntilFutureDate)
resultLabel.text = "Only \(dayString) days to go!"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment