How to calculate age with days/month/year using date picker? [duplicate] - swift

I am trying calculate the age from birthdayDate in Swift with this function:
var calendar : NSCalendar = NSCalendar.currentCalendar()
var dateComponentNow : NSDateComponents = calendar.components(
NSCalendarUnit.CalendarUnitYear,
fromDate: birthday,
toDate: age,
options: 0)
But I get an error Extra argument toDate in call
In objective c this was the code, but I don't know why get this error:
NSDate* birthday = ...;
NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthday
toDate:now
options:0];
NSInteger age = [ageComponents year];
Is there correct form better than this?

You get an error message because 0 is not a valid value for NSCalendarOptions.
For "no options", use NSCalendarOptions(0) or simply nil:
let ageComponents = calendar.components(.CalendarUnitYear,
fromDate: birthday,
toDate: now,
options: nil)
let age = ageComponents.year
(Specifying nil is possible because NSCalendarOptions conforms to the RawOptionSetType protocol which in turn inherits
from NilLiteralConvertible.)
Update for Swift 2:
let ageComponents = calendar.components(.Year,
fromDate: birthday,
toDate: now,
options: [])
Update for Swift 3:
Assuming that the Swift 3 types Date and Calendar are used:
let now = Date()
let birthday: Date = ...
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!

I create this method its very easy just put the birthday date in the method and this will return the Age as a Int
Swift 3
func calcAge(birthday: String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
let age = calcAge.year
return age!
}
Swift 2
func calcAge(birthday: String) -> Int{
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.dateFromString(birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.Year, fromDate: birthdayDate!, toDate: now, options: [])
let age = calcAge.year
return age
}
Usage
print(calcAge("06/29/1988"))

For swift 4 works fine
func getAgeFromDOF(date: String) -> (Int,Int,Int) {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "YYYY-MM-dd"
let dateOfBirth = dateFormater.date(from: date)
let calender = Calendar.current
let dateComponent = calender.dateComponents([.year, .month, .day], from:
dateOfBirth!, to: Date())
return (dateComponent.year!, dateComponent.month!, dateComponent.day!)
}
let age = getAgeFromDOF(date: "2000-12-01")
print("\(age.0) Year, \(age.1) Month, \(age.2) Day")

This works for Swift 3
let myDOB = Calendar.current.date(from: DateComponents(year: 1994, month: 9, day: 10))!
let myAge = Calendar.current.dateComponents([.month], from: myDOB, to: Date()).month!
let years = myAge / 12
let months = myAge % 12
print("Age : \(years).\(months)")

This is working in swift 3 for me..
let now = NSDate()
let calendar : NSCalendar = NSCalendar.current as NSCalendar
let ageComponents = calendar.components(.year, from: datePickerView.date, to: now as Date, options: [])
let age = ageComponents.year!
ageCalculated.text = String(age)
Thanks to #Martin R

//Create string extension to make more easy
extension String {
func getDate(format: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self) ?? Date()
}
}
Get today's date and your birthday date
let today = Date()
let birthDate = "1990-01-01".getDate(format: "yyyy-MM-dd")
Create an instance of the user's current calendar
let calendar = Calendar.current
Use calendar to get difference between two dates
let components = calendar.dateComponents([.year, .month, .day], from: birthDate, to: today)
let ageYears = components.year //get how many years old
let ageMonths = components.month //extra months
let ageDays = components.day // extra days

This is the best way on swift 5
lazy var dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
let birthday = dateFormatter.date(from: "1980-04-25")
let timeInterval = birthday?.timeIntervalSinceNow
let age = abs(Int(timeInterval! / 31556926.0))

Related

How do you get all the 4 (or 5) separate weeks in a month from Date() in swift?

I managed to get data query with "nextDate" property of type Date() in a particular month. In other words all data with dates within that particular month will appear on my tableview when queried. Using the code below and with tweaks I also managed to extract data from the previous and next month.
func loadMonthEvents() {
let date = Date()
let calendar = Calendar.current
var beginningOfMonth: Date?
var endOfMonth: Date?
beginningOfMonth = calendar.dateInterval(of: .month, for: date)?.start
endOfMonth = calendar.dateInterval(of: .month, for: date)?.end
monthEvents = realm.objects(Events.self).filter("nextDate BETWEEN %#", [beginningOfMonth, endOfMonth]).sorted(byKeyPath: "nextDate", ascending: true)
}
Now I want to be able to separate those data according to the week of the month. In my tableView the will be 5 separate headers representing week 1, week 2, week 3, week 4 and week 5(if any). Each separate header will show only event for that week. I tried to apply the weekOfMonth in calendar but it just dont work. Thank you in advance.
You could get the range of weeks from your two dates by doing
let w1 = calendar.dateComponents([.weekOfYear], from: beginningOfMonth!)
print(w1.weekOfYear)
let w2 = calendar.dateComponents([.weekOfYear], from: endOfMonth!)
print(w2.weekOfYear)
And then you could do the same for the date of each event to group the event to a specifik week
Here is the snippet to find out first and last day of week . You can do this by adding .weekOfMonth to the date component . Go through this official link and apply accordingly as per your requirement for fetch.
Now i had added two functions / or two button action through which you can get previous week and next week of the month.
var currentDate = Date()
func weekCalculation()
{
let calendar = NSCalendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// dateFormatter.dateStyle = .medium
var componentsNow = calendar.dateComponents([.year, .month, .weekOfMonth, .weekday], from: currentDate)
componentsNow.setValue(1, for: .weekday)
firstDayOfWeek = calendar.date(from: componentsNow)!
print(firstDayOfWeek)
componentsNow.setValue(7, for: .weekday)
lastDayOfWeek = calendar.date(from: componentsNow)!
print(lastDayOfWeek)
let addDaysCount = 0
var comps = DateComponents()
comps.setValue(addDaysCount, for: .weekday)
var comps1 = DateComponents()
comps1.setValue(-6, for: .day)
let newDate1 = calendar.date(byAdding: comps1, to: lastDayOfWeek)
let newDate2 = calendar.date(byAdding: comps, to: lastDayOfWeek)
// print(newDate1!,newDate2!)
let firstDay = dateFormatter.string(from: newDate1!)
let lastDay = dateFormatter.string(from: newDate2!)
// ShowBanner(title: "", subtitle: firstDay)
let dF = DateFormatter()
dF.dateFormat = "d MMMM yyyy"
let fDayToShow = dF.string(from: newDate1!)
let lDayToShow = dF.string(from: newDate2!)
let dateString = String(format: "%# - %#",fDayToShow,lDayToShow)
print(firstDay,lastDay)
}
#IBAction func nextWeekBtnPressed(sender: UIButton)
{
let calendar = NSCalendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// dateFormatter.dateStyle = .medium
let dF = DateFormatter()
dF.dateFormat = "d MMMM yyyy"
let addDaysCount = 7
var comps = DateComponents()
comps.setValue(addDaysCount, for: .weekday)
var comps1 = DateComponents()
comps1.setValue(3, for: .day)
let newDate1 = calendar.date(byAdding: comps1, to: lastDayOfWeek)
let newDate2 = calendar.date(byAdding: comps, to: lastDayOfWeek)
let firstDay = dateFormatter.string(from: newDate1!)
let lastDay = dateFormatter.string(from: newDate2!)
let fDayToShow = dF.string(from: newDate1!)
let lDayToShow = dF.string(from: newDate2!)
//print(firstDay,lastDay)
let dateString = String(format: "%# - %#",fDayToShow,lDayToShow)
//print(dateString)
weekCalculation()
}
#IBAction func previousWeekBtnPressed(sender: UIButton)
{
let calendar = NSCalendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// dateFormatter.dateStyle = .medium
let addDaysCount = -7
var comps = DateComponents()
comps.setValue(addDaysCount, for: .weekday)
var comps1 = DateComponents()
comps1.setValue(-10, for: .day)
let newDate1 = calendar.date(byAdding: comps1, to: lastDayOfWeek)
let newDate2 = calendar.date(byAdding: comps, to: lastDayOfWeek)
let firstDay = dateFormatter.string(from: newDate1!)
let lastDay = dateFormatter.string(from: newDate2!)
let dF = DateFormatter()
dF.dateFormat = "d MMMM yyyy"
let fDayToShow = dF.string(from: newDate1!)
let lDayToShow = dF.string(from: newDate2!)
let dateString = String(format: "%# - %#",fDayToShow,lDayToShow)
weekCalculation()
}

Calculate age from birth date using textfield and NSDateComponents in Swift4

I am trying calculate the age from birthday Date in Swift with this function: (want to write in a textField and pass this data from VC in a Label)
{
var a = self.dob.text
var c = a!.components(separatedBy: "-")
var y1 = c[2]
let cal = NSCalendar? = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let year = Calendar.components(.year, from: dob!, to: now, options: [])
let age = (year!) - Int(y1)!
self.myage.text = String(age)
}
But I get an error cannot assign NSCalendar?.Type, but I don't know why get this error (its my first time coding)
You have a few problems in your code. First there is a type as already mentioned by Qi Hao, second you are passing dob is a text field you and Calendar components method expects two dates, so you should first parse the text field date then you can get the year component difference from input date and now:
Playground Testing
let dob = UITextField()
dob.text = "03-27-2002"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MM-dd-yyyy"
if let date = dateFormatter.date(from: dob.text!) {
let age = Calendar.current.dateComponents([.year], from: date, to: Date()).year!
print(age) // 16
}
func age(on baseDate: DateComponents) -> Int {
if baseDate.month > month {
return baseDate.year - year
}
if baseDate.month == month && baseDate.day >= day {
return baseDate.year - year
}
return baseDate.year - year - 1
}
try this:
func calcAge(birthday: String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
let age = calcAge.year
return age!
}

Convert facebook birthday to age swift

When retrieving birthday from the Facebook SDK i get this string "01/12/1990".
My question is, how would you convert the birthday into the age of the user using this string?
Swift 4
My use case is also for Facebook and I have used UserDefaults to store the birthdate. The below function will retrieve birthdate from UserDefaults, as returned by the graphRequest which is in the same format as your Date. The function will return an Integer with the user's age.
func getAgeFromBirthdate() -> Int {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let birthday = UserDefaults.standard.object(forKey: "birthday")
let birthdayString = birthday as! String
let birthdate = dateFormatter.date(from: birthdayString)
let currentDate = Date()
let calendar: Calendar = Calendar(identifier: .gregorian)
let age = calendar.component(.year, from: birthdate!).distance(to: calendar.component(.year, from: currentDate))
return age
}
func yearsBetween(date1: Date, date2: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.year], from: date1, to: date2)
return components.year ?? 0
}
// Get Age
let dateString = "01/12/1990"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let date1 = dateFormatter.date(from: dateString)
let date2 = Date()
let age = self.daysBetween(date1:date1!, date2:date2)
Hope it will help you.
You can do a little more Google before ask, also you may find these answers helpful:
How do you create a swift Date object
Calculate age from birth date using NSDateComponents in Swift
func calcAge(birthday:String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now as Date, options: [])
let age = calcAge.year
return age!
}
usage:
print(calcAge(birthday: "01/12/1990"))

Get just the date (no time) from UIDatePicker

I am trying to get just the date from UIDatePicker:
myDatePicker.datePickerMode = UIDatePicker.Mode.date
var selectedDate=myDatePicker.date
println(selectedDate)
However, this prints more than the date (it prints 2015-04-09 21:45:13 +0000). How do I get just the date part (without the time)? I also set the date picker Mode property to Date.
According to the Apple's documentation datePicker.mode should be date so you can use DateFormatter like so
Swift 4
datePicker.datePickerMode = UIDatePicker.Mode.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy"
let selectedDate = dateFormatter.string(from: datePicker.date)
print(selectedDate)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yy"
let dateString = dateFormatter.stringFromDate(myDatePicker.date)
You can print dateString, assign it to a label, whatever. The format will be
04/09/15
Swift 3/4, this will print a string of type Mar 08, 2017
datePicker.datePickerMode = .date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let selectedDate = dateFormatter.string(from: datePicker.date)
print(selectedDate)
I just want to add my bit in on here after coming across a similar problem. I would follow shades answer for String display of date. Not the from XCode 7 and swift 2 onwards when you use a UIDatePicker set the following to only view dates in the Picker:
#IBOutlet weak var datePicker: UIDatePicker!
datePicker.datePickerMode = .Date
Swift 4.0 version code is here
#IBAction func saveDateAction(_ sender: Any) {
myDatePicker.datePickerMode = UIDatePicker.Mode.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
let selectedDate = dateFormatter.string(from: myDatePicker.date)
print("selectedDate",selectedDate)
}
Date picker date :
let date = datePicker.date
let dateConverted = Date.init(year: date.GetYear(), month: date.GetMonth(), day: date.GetDay())
//dateConverted result = 2019-02-27 00:00:00 +0000
let predicate = NSPredicate(format: "booking_date == %#", dateConverted as CVarArg)
Use this extensions:
extension Date {
init(year: Int, month: Int, day: Int) {
var dc = DateComponents()
dc.year = year
dc.month = month
dc.day = day
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
if let date = calendar.date(from: dc) {
self.init(timeInterval: 0, since: date)
} else {
fatalError("Date component values were invalid.")
}
}
func GetYear() -> Int {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar.components([.day , .month , .year], from: self)
return components.year!
}
func GetMonth() -> Int {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar.components([.day , .month , .year], from: self)
return components.month!
}
func GetDay() -> Int {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar.components([.day , .month , .year], from: self)
return components.day!
}
}

Calculate age from birth date using NSDateComponents in Swift

I am trying calculate the age from birthdayDate in Swift with this function:
var calendar : NSCalendar = NSCalendar.currentCalendar()
var dateComponentNow : NSDateComponents = calendar.components(
NSCalendarUnit.CalendarUnitYear,
fromDate: birthday,
toDate: age,
options: 0)
But I get an error Extra argument toDate in call
In objective c this was the code, but I don't know why get this error:
NSDate* birthday = ...;
NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthday
toDate:now
options:0];
NSInteger age = [ageComponents year];
Is there correct form better than this?
You get an error message because 0 is not a valid value for NSCalendarOptions.
For "no options", use NSCalendarOptions(0) or simply nil:
let ageComponents = calendar.components(.CalendarUnitYear,
fromDate: birthday,
toDate: now,
options: nil)
let age = ageComponents.year
(Specifying nil is possible because NSCalendarOptions conforms to the RawOptionSetType protocol which in turn inherits
from NilLiteralConvertible.)
Update for Swift 2:
let ageComponents = calendar.components(.Year,
fromDate: birthday,
toDate: now,
options: [])
Update for Swift 3:
Assuming that the Swift 3 types Date and Calendar are used:
let now = Date()
let birthday: Date = ...
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!
I create this method its very easy just put the birthday date in the method and this will return the Age as a Int
Swift 3
func calcAge(birthday: String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
let age = calcAge.year
return age!
}
Swift 2
func calcAge(birthday: String) -> Int{
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.dateFromString(birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.Year, fromDate: birthdayDate!, toDate: now, options: [])
let age = calcAge.year
return age
}
Usage
print(calcAge("06/29/1988"))
For swift 4 works fine
func getAgeFromDOF(date: String) -> (Int,Int,Int) {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "YYYY-MM-dd"
let dateOfBirth = dateFormater.date(from: date)
let calender = Calendar.current
let dateComponent = calender.dateComponents([.year, .month, .day], from:
dateOfBirth!, to: Date())
return (dateComponent.year!, dateComponent.month!, dateComponent.day!)
}
let age = getAgeFromDOF(date: "2000-12-01")
print("\(age.0) Year, \(age.1) Month, \(age.2) Day")
This works for Swift 3
let myDOB = Calendar.current.date(from: DateComponents(year: 1994, month: 9, day: 10))!
let myAge = Calendar.current.dateComponents([.month], from: myDOB, to: Date()).month!
let years = myAge / 12
let months = myAge % 12
print("Age : \(years).\(months)")
This is working in swift 3 for me..
let now = NSDate()
let calendar : NSCalendar = NSCalendar.current as NSCalendar
let ageComponents = calendar.components(.year, from: datePickerView.date, to: now as Date, options: [])
let age = ageComponents.year!
ageCalculated.text = String(age)
Thanks to #Martin R
//Create string extension to make more easy
extension String {
func getDate(format: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self) ?? Date()
}
}
Get today's date and your birthday date
let today = Date()
let birthDate = "1990-01-01".getDate(format: "yyyy-MM-dd")
Create an instance of the user's current calendar
let calendar = Calendar.current
Use calendar to get difference between two dates
let components = calendar.dateComponents([.year, .month, .day], from: birthDate, to: today)
let ageYears = components.year //get how many years old
let ageMonths = components.month //extra months
let ageDays = components.day // extra days
This is the best way on swift 5
lazy var dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
let birthday = dateFormatter.date(from: "1980-04-25")
let timeInterval = birthday?.timeIntervalSinceNow
let age = abs(Int(timeInterval! / 31556926.0))