// ImportantBirthdays.swift Copyright (c) Kari Laitinen // http://www.naturalprogramming.com // 2015-10-08 File created. // 2016-11-09 Last modification. // This program demonstrates: // - use of standard types Date, Calendar, etc. import Foundation // The following extension to Date was written based on // the advice in address // http://stackoverflow.com/questions/24089999/how-do-you-create-a-swift-date-object extension Date { init( _ date_as_string: String ) { let date_formatter = DateFormatter() date_formatter.dateFormat = "yyyy-MM-dd" date_formatter.locale = Locale( identifier: "en_US_POSIX" ) let date_object = date_formatter.date( from: date_as_string )! self.init( timeInterval: 0, since: date_object ) } } let calendar = Calendar.current print( "\n Type in your date of birth as YYYY-MM-DD" + "\n Use four digits for the year and two digits" + "\n for the month and day: ", terminator: "" ) let date_of_birth_as_string = readLine()! let date_of_birth = Date( date_of_birth_as_string ) let day_of_week_of_birthday = calendar.component( Calendar.Component.weekday, from: date_of_birth ) let date_formatter = DateFormatter() print( "\n You were born on a " + date_formatter.weekdaySymbols[ day_of_week_of_birthday - 1 ] ) print( " Here are your days to celebrate. You are \n" ) let year_of_birthday = calendar.component( Calendar.Component.year, from: date_of_birth ) let month_of_birthday = calendar.component( Calendar.Component.month, from: date_of_birth ) let day_of_birthday = calendar.component( Calendar.Component.day, from: date_of_birth ) var years_to_celebrate = 10 while years_to_celebrate < 80 { var celebration_day_components = DateComponents() celebration_day_components.year = year_of_birthday + years_to_celebrate celebration_day_components.month = month_of_birthday celebration_day_components.day = day_of_birthday celebration_day_components.hour = 14 // Two o'clock in the afternoon. let date_to_celebrate = calendar.date( from: celebration_day_components )! print( String( format: " %d years old on %04d-%02d-%02d (", years_to_celebrate, year_of_birthday + years_to_celebrate, month_of_birthday, day_of_birthday ), terminator: "" ) let day_of_week_of_celebration_date = calendar.component( Calendar.Component.weekday, from: date_to_celebrate ) print( date_formatter.weekdaySymbols[ day_of_week_of_celebration_date - 1 ] + ")" ) years_to_celebrate = years_to_celebrate + 10 } print( "\n" )