我正在制作一个应用程序,需要根据他们的生日找到某人的年龄。我有一个简单的NSDate
,但我如何通过NSDateFormatter
找到它?
答案 0 :(得分:24)
- (NSInteger)ageFromBirthday:(NSDate *)birthdate {
NSDate *today = [NSDate date];
NSDateComponents *ageComponents = [[NSCalendar currentCalendar]
components:NSCalendarUnitYear
fromDate:birthdate
toDate:today
options:0];
return ageComponents.year;
}
NSDateFormatter
用于格式化日期(呃!)。根据经验,只要您需要对NSDate
执行某些计算,就可以使用NSCalendar
及相关类,例如NSDateComponents
。
答案 1 :(得分:2)
NSYearCalendarUnit 已弃用。它被 NSCalendarUnitYear
取代- (NSString *) ageFromBirthDate:(NSString *)birthDate{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *myDate = [dateFormatter dateFromString: birthDate];
return [NSString stringWithFormat:@"%d ans", [[[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:myDate toDate:[NSDate date] options:0] year]];
}
答案 2 :(得分:0)
如果你只是想知道某个人的年龄,我找到了一个较短的方法去做你想要完成的事情。
- (NSInteger)ageFromBirthday:(NSDate *)birthdate {
NSDate *today = [NSDate date];
NSInteger ageOfPerson = today.year - birthdate.year;
return ageofPerson;
}
答案 3 :(得分:0)
检查一下,我用过 " (NSDateComponents *)组件:(NSCalendarUnit)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSCalendarOptions)opts " 并添加了本地化
Sub PasteValuesSummary()
Dim LookupValue As String
Dim LookupRange As Range
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Summary")
Set LookupRange = Sheets("Summary").Range("B1:B1000")
LookupValue = Sheets("LastUpdate").Range("A1").Value
If Not IsError(Application.Match(LookupValue, LookupRange, 0)) Then
Sheets("Summary").Select
Sheets("Summary").Rows("4:4").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Sheets("Summary").Range("B4").Select
Sheets("Summary").Range("B4") = "=LastUpdate!R[-3]C[-1]"
Sheets("Summary").Range("C2:AP2").Select
Selection.Copy
ActiveWindow.ScrollColumn = 1
Sheets("Summary").Range("C4").Select
Sheets("Summary").Paste
Application.CutCopyMode = False
Selection.Copy
Sheets("Summary").Range("B4:AP4").Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
End Sub