简体   繁体   English

获取日历天中两个日期之间的差异

[英]Get the difference between two dates in calendar days

can anyone explain how can I get difference between two dates in calendar days, not in whole 24-hour periods.谁能解释我如何在日历日而不是整个 24 小时内获得两个日期之间的差异。 There is a good solution here: Getting the difference between two NSDates in (months/days/hours/minutes/seconds) -- but it doesn't work for me as, for example, it gives the difference between 23:00 today and 1:30 tomorrow as 0 days despite of calendar dates differ already by 1.这里有一个很好的解决方案: 在(月/天/小时/分钟/秒)中获取两个 NSDates 之间的差异- 但它对我不起作用,例如,它给出了今天 23:00 和明天 1:30 为 0 天,尽管日历日期已经相差 1。

Use the normal way to calculate the difference in days with one change - convert both of your dates to midnight.使用正常方法计算一次更改的天数差异 - 将两个日期都转换为午夜。

let d1 = ... // your first date
let d2 = ... // your second date
let cal = Calendar.current
let days = cal.dateComponents([.day], from: cal.startOfDay(for: d1), to: cal.startOfDay(for: d2)).day!

This will give an answer of 1 for "yesterday at 23:00" and "today at 1:30", for example.例如,这将给出“昨天 23:00”和“今天 1:30”的答案1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM