두 날짜 간의 시간 차이를 계산 중입니다. 나는 코드 조각이 :Swift의 DateComponents가 이상한 값을 반환합니다. 왜?
func timeAgoSinceDate(_ date:Date, numericDates:Bool) -> String {
let calendar = Calendar.current
let now = Date()
let components:DateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.minute , NSCalendar.Unit.hour , NSCalendar.Unit.day , NSCalendar.Unit.weekOfYear , NSCalendar.Unit.month , NSCalendar.Unit.year , NSCalendar.Unit.second], from: now, to: date, options: NSCalendar.Options())
print(now)
print(date)
print(components.month)
을하고 사람들은 내가 콘솔에서보고 있어요 몇 가지 예입니다 :
2016-10-29 16:12:34 +0000
2017-03-29 16:03:13 +0000
Optional(4) //I think it should return 5?
2016-10-29 16:12:34 +0000
2017-01-29 17:03:13 +0000
Optional(2) //again, why 2 instead of 3?
2016-10-29 16:12:34 +0000
2015-09-30 15:54:20 +0000
Optional(0) //why 0 since it's almost whole year?
2016-10-29 16:12:34 +0000
2016-05-29 14:09:31 +0000
Optional(-5) //this seems to be fine
등등 ... 무슨 문제가?
문제점은 날짜 계산과 관련되어 있습니다. 내 코드에서 내가 뭘 하나 날짜가 2016-10-29 16:32:54 +0000
이고, 다른 하나는 2017-01-29 17:03:13 +0000
때 때문에 내 계산을 수행의 다음
if (components.month! >= 2) {
return "in \(components.month!) months"
} else if (components.month! >= 1){
if (numericDates){
return "in 1 month"
} else {
return "in one month"
}
}
else if (components.month! <= -2) {
return "\(components.month!) months ago"
} else if (components.month! <= -1){
if (numericDates){
return "1 month ago"
} else {
return "one month ago"
}
}
을하고, 현재 사용자는 in 2 months
을 본다. 그 때문에 전체 print(components)
반환 :
year: 0 month: 2 day: 2 hour: 23 minute: 30 second: 18 weekOfYear: 4 isLeapMonth: false
하지만 10 월 월 사이의 차이이기 때문에 실생활에 3을 반환해야합니다. 이 차이를 계산하는 더 좋은 방법은 if
문장을 모두 내리는 것보다 낫지 않습니까? 이 5
2016-10-29 16:12:34 +0000
2017-01-29 17:03:13 +0000
Optional(2) //again, why 2 instead of 3?
일광 절약 시간을 반환하기 전에 16시 3분 이후
현재 시간대는 무엇입니까? 날짜는 UTC/GMT로 인쇄되지만 달력 계산은 로컬 달력/시간대에서 수행됩니다. * –
첫 번째 예제에서는 지정된 날짜 사이에 * 5 개월 미만이므로 결과 4가 정확합니다. –
hm하지만 시간대가'months'의 경우 계산에 영향을 미치지 않아야한다고 생각했습니다 ... 어쨌든'GMT + 1'에 있는데, 시간대와 독립적으로 계산을 수행 할 수있는 방법이 있습니까? – user3766930