根据字符串swift计算年龄



我试图计算从婴儿到成年人的任何年龄段的人(例如8周大、4个月大或22岁(。但是我的计算错误了,找不到哪里。如果我将出生日期输入为2020年10月16日,它将返回8周大,这是正确的。然而,如果我输入2020年10月26日,它会返回11周大,这是不正确的。非常感谢您的帮助。

年龄函数:

let bornOn = "10/16/2020"
func calculateAge(dob: String, format: String = "MM/dd/yyyy") -> String{
let df = DateFormatter()
df.dateFormat = format
let date = df.date(from: dob)
guard let val = date else{
return ""
}
var years = 0
var months = 0
var days = 0

let cal = Calendar.current
years = cal.component(.year, from: Date()) - cal.component(.year, from: val)

let currentMonth = cal.component(.month, from: Date())
let birthMonth = cal.component(.month, from: val)

months = currentMonth - birthMonth

if months < 0 {
years = years - 1
months = 12 - birthMonth
if cal.component(.day, from: Date()) < cal.component(.day, from: val){
months = months - 1
}
}else if months == 0 && cal.component(.day, from: Date()) < cal.component(.day, from: val){
years = years - 1
months = 11
}
if cal.component(.day, from: Date()) > cal.component(.day, from: val){
days = cal.component(.day, from: Date()) - cal.component(.day, from: val)
}else if cal.component(.day, from: Date()) < cal.component(.day, from: val){
let today = cal.component(.day, from: Date())
let date = cal.date(byAdding: .month, value: -1, to: Date())
days = date!.daysInMonth - cal.component(.day, from: val) + today
}else{
days = 0
if months == 12 {
years = years + 1
months = 0
}
}
print("Years: (years), Months: (months), Days: (days)")
if years > 0{
if years == 1{
return "(years) year old"
}else{
return "(years) years old"
}
}else if months > 4{
return "(months) months old"
}else {
if  months >= 1{
let daysleftInMonth = months * 30
print(daysleftInMonth)
days += daysleftInMonth
}

let weeks = days / 7
return "(weeks) weeks old"
}
}
extension Date{
var daysInMonth:Int{
let calendar = Calendar.current

let dateComponents = DateComponents(year: calendar.component(.year, from: self), month: calendar.component(.month, from: self))
let date = calendar.date(from: dateComponents)!

let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count

return numDays
}
}
calculateAge(dob: bornOn)

你走错了方向。您需要的是解析日期字符串,将其转换为日期,并使用DateComponentsFormatter来显示此人的年龄。您还可以获得从生日到今天的日期组件:

extension Formatter {
static let dateMMddyyyy: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = .init(identifier: "en_US_POSIX")
formatter.dateFormat = "MM/dd/yyyy"
return formatter
}()
static let dateComponents: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.day, .month, .year]
formatter.maximumUnitCount = 1
return formatter
}()
}

extension Date {
var ageComponents: DateComponents { Calendar.current.dateComponents([.year, .month, .day], from: self, to: Date()) }
var relativeAge: String {
Formatter.dateComponents.allowedUnits = ageComponents.month! >= 2 ?
[.day, .month, .year] : [.weekOfMonth]
return Formatter.dateComponents.string(from: self, to: Date())! 
}
}

extension String {
var dateFromMMddyyyy: Date? { Formatter.dateMMddyyyy.date(from: self) }
}

"09/10/1970".dateFromMMddyyyy?.relativeAge  // "50 years"
"10/16/2020".dateFromMMddyyyy?.relativeAge  // "2 months"
"10/23/2020".dateFromMMddyyyy?.relativeAge  // "7 weeks"
extension Date {
func timeAgo() -> String {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.year, .month, .weekOfMonth ,.day, .hour, .minute, .second]
formatter.zeroFormattingBehavior = .dropAll
formatter.maximumUnitCount = 1
return String(format: formatter.string(from: self, to: Date()) ?? "", locale: .current)
}
}

在您的方法中使用上述日期扩展

func calculateAge(dob: String, format: String = "MM/dd/yyyy") -> String{
let df = DateFormatter()
df.dateFormat = format
let date = df.date(from: dob)
return date?.timeAgo() ?? ""
}

像一样使用它

let date = calculateAge(dob: bornOn)
print(date) //print - 2 weeks

相关内容

  • 没有找到相关文章

最新更新