将时间字符串转换为时间间隔字符串的最佳方法
Best Way to Convert Time String to Time Interval String
我有一个以“下午 5 点 35 分”的形式显示出发时间的应用程序,我想添加一个选项以从现在开始以间隔的形式显示时间,例如:“23 分钟”。
我是 swift 的新手,我仍在努力处理日期和日期格式化程序
实现此目的的一种方法是将 Date
class 差异扩展到 return - 尽管您只显示分钟,但您应该能够处理“3 天”这样的时间间隔, 2 小时 23 分钟” - 当然,您可以选择将其显示为“3 天”,或者 "more than 51 hours"
extension Date
{
func differenceInDays(date: Date) -> Int
{
return Calendar.current.dateComponents([.day], from: self, to: date).day!
}
func differenceInHours(date: Date) -> Int
{
// returns the TOTAL number of hours, not just the hour component
return Calendar.current.dateComponents([.hour], from: self, to: date).hour!
}
func differenceInMinutes(date: Date) -> Int
{
// returns the TOTAL number of minutes, not just the minute component
return Calendar.current.dateComponents([.minute], from: self, to: date).minute!
}
}
我有一个以“下午 5 点 35 分”的形式显示出发时间的应用程序,我想添加一个选项以从现在开始以间隔的形式显示时间,例如:“23 分钟”。
我是 swift 的新手,我仍在努力处理日期和日期格式化程序
实现此目的的一种方法是将 Date
class 差异扩展到 return - 尽管您只显示分钟,但您应该能够处理“3 天”这样的时间间隔, 2 小时 23 分钟” - 当然,您可以选择将其显示为“3 天”,或者 "more than 51 hours"
extension Date
{
func differenceInDays(date: Date) -> Int
{
return Calendar.current.dateComponents([.day], from: self, to: date).day!
}
func differenceInHours(date: Date) -> Int
{
// returns the TOTAL number of hours, not just the hour component
return Calendar.current.dateComponents([.hour], from: self, to: date).hour!
}
func differenceInMinutes(date: Date) -> Int
{
// returns the TOTAL number of minutes, not just the minute component
return Calendar.current.dateComponents([.minute], from: self, to: date).minute!
}
}