Есть ли в Swift функция PrettyTime
В моем приложении для Android я использую следующий код, чтобы получить строку, которая преобразует дату в удобочитаемое предложение (см. Изображение ниже). Есть ли способ сделать это Swift 4.2?
private String getDate(String d) {
String datemobile = "";
try {
String section1 = null;
String mydateStr = null;
DateFormat df1 = null;
PrettyTime p = new PrettyTime();
Date date = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
df1 = new SimpleDateFormat("EEE, d MMM yyyy ");
date = df.parse(d);
mydateStr = df1.format(date);
datemobile = p.format(date) + " on " + mydateStr;
return datemobile;
} catch (Exception e) {
e.printStackTrace();
return datemobile;
}
}
3 ответа
Нашел ЭТО, но это для прошлых дат, поэтому я обновил его для будущих дат согласно вашему требованию.
Проверьте ниже пример:
//Future date
let date1 = DateComponents(calendar: .current, year: 2019, month: 3, day: 20, hour: 5, minute: 9).date!
extension Date {
func futureDateDisplay() -> String {
let calendar = Calendar.current
let minutesUntil = calendar.date(byAdding: .minute, value: 1, to: Date())!
let hourUntil = calendar.date(byAdding: .hour, value: 1, to: Date())!
let dayUntil = calendar.date(byAdding: .day, value: 1, to: Date())!
let weekUntil = calendar.date(byAdding: .day, value: 7, to: Date())!
if minutesUntil > self {
let diff = Calendar.current.dateComponents([.second], from: Date(), to: self).second ?? 0
return "\(diff) sec from now on"
} else if hourUntil > self {
let diff = Calendar.current.dateComponents([.minute], from: Date(), to: self).minute ?? 0
return "\(diff) min from now on"
} else if dayUntil > self {
let diff = Calendar.current.dateComponents([.hour], from: Date(), to: self).hour ?? 0
return "\(diff) hrs from now on"
} else if weekUntil > self {
let diff = Calendar.current.dateComponents([.day], from: Date(), to: self).day ?? 0
return "\(diff) days from now on"
}
let diff = Calendar.current.dateComponents([.weekOfYear], from: Date(), to: self).weekOfYear ?? 0
return "\(diff) weeks from now on"
}
}
И вы можете использовать его как:
date1.futureDateDisplay() //4 weeks from now on
Или вот решение для сортировки для этого:
let date1 = DateComponents(calendar: .current, year: 2019, month: 3, day: 20, hour: 5, minute: 9).date!
extension Date {
func futureDateDisplay() -> String {
let remainingTime = DateComponentsFormatter()
let calendar = Calendar.current
remainingTime.calendar = calendar
remainingTime.unitsStyle = .full
remainingTime.allowedUnits = [.month,.weekOfMonth, .day, .hour, .minute, .second]
remainingTime.maximumUnitCount = 1
return remainingTime.string(from: Date(), to: self)!
}
}
date1.futureDateDisplay() // 1 month, 1 day
Используйте следующую функцию, чтобы получить строку через 2 месяца как ваше требование.
В этой функции передайте NSDate, и он обнаружит разницу и вернет формат строки, например, через 2 недели, через 3 месяца и т. Д.
func getDateStringForDate(date : NSDate) -> NSString {
let todayDate = NSDate()
let units: NSCalendarUnit = [.Hour, .Day, .Month, .Year, .WeekOfYear]
let components = NSCalendar.currentCalendar().components(units, fromDate: date , toDate: todayDate, options: NSCalendarOptions.MatchFirst )
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let weeks = components.weekOfYear
// if `date` is before "now" (i.e. in the past) then the components will be positive
if components.year > 0 {
return NSString.init(format: "%d years from now on", year);
} else if components.month > 0 {
return NSString.init(format: "%d months from now on", month);
} else if components.weekOfYear > 0 {
return NSString.init(format: "%d weeks from now on", weeks);
} else if (components.day > 0) {
if components.day > 1 {
return NSString.init(format: "%d days from now on", day);
} else {
return "Yesterday";
}
} else {
return NSString.init(format: "%d hours from now on", hour);
}
}
Попробуй это,
let startDateString = "03/01/2019" // start date
let endDateString = "15/03/2019" // end date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let startDate = dateFormatter.date(from: startDateString)
let endDate = dateFormatter.date(from: endDateString)
let gregorian = NSCalendar(calendarIdentifier:NSCalendar.Identifier.gregorian)
let c2 = gregorian?.components([.minute, .hour, .weekOfMonth , .day, .month, .year], from: startDate!, to: endDate!, options: .matchFirst)
print(c2)
Ссылка: https://developer.apple.com/documentation/foundation/nscalendar/unit
Выход: