Calculate age from birth date using NSDateComponents in Swift
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!
How to calculate age (in years) based on Date of Birth and getDate()
There are issues with leap year/days and the following method, see the update below:
try this:
DECLARE @dob datetime
SET @dob='1992-01-09 00:00:00'
SELECT DATEDIFF(hour,@dob,GETDATE())/8766.0 AS AgeYearsDecimal
,CONVERT(int,ROUND(DATEDIFF(hour,@dob,GETDATE())/8766.0,0)) AS AgeYearsIntRound
,DATEDIFF(hour,@dob,GETDATE())/8766 AS AgeYearsIntTrunc
OUTPUT:
AgeYearsDecimal AgeYearsIntRound AgeYearsIntTrunc
--------------------------------------- ---------------- ----------------
17.767054 18 17
(1 row(s) affected)
UPDATE here are some more accurate methods:
BEST METHOD FOR YEARS IN INT
DECLARE @Now datetime, @Dob datetime
SELECT @Now='1990-05-05', @Dob='1980-05-05' --results in 10
--SELECT @Now='1990-05-04', @Dob='1980-05-05' --results in 9
--SELECT @Now='1989-05-06', @Dob='1980-05-05' --results in 9
--SELECT @Now='1990-05-06', @Dob='1980-05-05' --results in 10
--SELECT @Now='1990-12-06', @Dob='1980-05-05' --results in 10
--SELECT @Now='1991-05-04', @Dob='1980-05-05' --results in 10
SELECT
(CONVERT(int,CONVERT(char(8),@Now,112))-CONVERT(char(8),@Dob,112))/10000 AS AgeIntYears
you can change the above 10000
to 10000.0
and get decimals, but it will not be as accurate as the method below.
BEST METHOD FOR YEARS IN DECIMAL
DECLARE @Now datetime, @Dob datetime
SELECT @Now='1990-05-05', @Dob='1980-05-05' --results in 10.000000000000
--SELECT @Now='1990-05-04', @Dob='1980-05-05' --results in 9.997260273973
--SELECT @Now='1989-05-06', @Dob='1980-05-05' --results in 9.002739726027
--SELECT @Now='1990-05-06', @Dob='1980-05-05' --results in 10.002739726027
--SELECT @Now='1990-12-06', @Dob='1980-05-05' --results in 10.589041095890
--SELECT @Now='1991-05-04', @Dob='1980-05-05' --results in 10.997260273973
SELECT 1.0* DateDiff(yy,@Dob,@Now)
+CASE
WHEN @Now >= DATEFROMPARTS(DATEPART(yyyy,@Now),DATEPART(m,@Dob),DATEPART(d,@Dob)) THEN --birthday has happened for the @now year, so add some portion onto the year difference
( 1.0 --force automatic conversions from int to decimal
* DATEDIFF(day,DATEFROMPARTS(DATEPART(yyyy,@Now),DATEPART(m,@Dob),DATEPART(d,@Dob)),@Now) --number of days difference between the @Now year birthday and the @Now day
/ DATEDIFF(day,DATEFROMPARTS(DATEPART(yyyy,@Now),1,1),DATEFROMPARTS(DATEPART(yyyy,@Now)+1,1,1)) --number of days in the @Now year
)
ELSE --birthday has not been reached for the last year, so remove some portion of the year difference
-1 --remove this fractional difference onto the age
* ( -1.0 --force automatic conversions from int to decimal
* DATEDIFF(day,DATEFROMPARTS(DATEPART(yyyy,@Now),DATEPART(m,@Dob),DATEPART(d,@Dob)),@Now) --number of days difference between the @Now year birthday and the @Now day
/ DATEDIFF(day,DATEFROMPARTS(DATEPART(yyyy,@Now),1,1),DATEFROMPARTS(DATEPART(yyyy,@Now)+1,1,1)) --number of days in the @Now year
)
END AS AgeYearsDecimal
How to compute age from NSDate
- (NSInteger)ageFromBirthday:(NSDate *)birthdate {
NSDate *today = [NSDate date];
NSDateComponents *ageComponents = [[NSCalendar currentCalendar]
components:NSCalendarUnitYear
fromDate:birthdate
toDate:today
options:0];
return ageComponents.year;
}
NSDateFormatter
is for formatting dates (duh!). As a rule of thumb, whenever you need to perform some computation on an NSDate
you use a NSCalendar
and associated classes, such as NSDateComponents
.
Calculate age from birth date
update: Xcode 11 • Swift 5.1
You can use the Calendar method dateComponents to calculate how many years from a specific date to today:
extension Date {
var age: Int { Calendar.current.dateComponents([.year], from: self, to: Date()).year! }
}
let dob = DateComponents(calendar: .current, year: 2000, month: 6, day: 30).date!
let age = dob.age // 19
How to calculate age from date of birth
If anyone here wants to get the difference between two dates in days and want to display it in another column in the JSP you can you can do like this.
<fmt:parseDate value = "${name_of_your_bean.1st_variable}" var = "formatedDate1" type = "date" pattern = "yyyy-MM-dd" />
<jsp:useBean id="start_date" class="java.util.Date" />
<td > <fmt:formatDate value = "${formatedDate1}" type = "date" pattern = "MMMM dd,yyyy"/> </td>
<fmt:parseDate value = "${name_of_your_bean.2nd_variable}" var = "formatedDate2" type = "date" pattern = "yyyy-MM-dd" />
<jsp:useBean id="end_date" class="java.util.Date" />
<td> <fmt:formatDate value = "${formatedDate2}" type = "date" pattern = "MMMM dd,yyyy"/> </td>
// To display in separate column do like this
<td> <fmt:parseNumber type = "number" integerOnly = "true" value = "${(formatedDate2.time - formatedDate1.time)/(1000 * 60 * 60 * 24)}" /> Days </td>
How do I calculate someone's age based on a DateTime type birthday?
An easy to understand and simple solution.
// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;
However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.
How do I get the age after using a date picker?
This will work fine for u
var birthday: NSDate = ..... //date that comes from date picker
var now: NSDate = NSDate()
var ageComponents: NSDateComponents = NSCalendar.currentCalendar().components(.Year, fromDate: birthday, toDate: now, options: 0)
var age: Int = ageComponents.year()
If u want to formate date you can use DateFormatter
Ex.
let usDateFormat = NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "en-US"))
//usDateFormat now contains an optional string "MM/dd/yyyy".
let gbDateFormat = NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "en-GB"))
//gbDateFormat now contains an optional string "dd/MM/yyyy"
formatter.dateFormat = usDateFormat
let usSwiftDayString = formatter.stringFromDate(swiftDay)
// usSwiftDayString now contains the string "06/02/2014".
formatter.dateFormat = gbDateFormat
let gbSwiftDayString = formatter.stringFromDate(swiftDay)
// gbSwiftDayString now contains the string "02/06/2014".
Related Topics
Avplayer Stops Playing Video After Buffering
Detect Hash Tags #, Mention Tags @, in iOS Like in Twitter App
Can an iOS App Switch to Safari Without Opening a Page
Xcode 7 How to Refresh Provisioning Profiles
Xcode6 Error: "No Matching Provisioning Profiles Found for Application"
What Does Inherit! :Search_Paths Do
Xcode: Could Not Inspect the Application Package
SkstoreReviewController, How to Use It in a Correct Way
Uialertcontroller Text Alignment
Swift 2.0 Minimum System Version Requirement (Deployment Target)
Use Uibarbuttonitem Icon in Uibutton
App Submission Binary Does Not Show Up in Itunes Connect
Expand and Collapse Tableview Cells
Showing a Uipickerview with Uiactionsheet in iOS8 Not Working
Xcode 4.3: Codesign Operation Failed (Check That the Identity You Selected Is Valid)
Prepareforsegue Called Before Didselectrowatindexpath Only When Third Segue Is Added