在一个单元格中,我想在Parse服务器中显示NSDate的时间。这是代码,但它不起作用。什么都没有改变,数据也没有被解析。
if let createdat = (object?["createdAt"] as? String){
let pastDate = Date(timeIntervalSinceNow: TimeInterval(createdat)!)
cell.TimeAgo.text = pastDate.timeAgoDisplay()
}
extension Date {
func timeAgoDisplay() -> String {
let secondsAgo = Int(Date().timeIntervalSince(self))
let minute = 60
let hour = 60 * minute
let day = 24 * hour
let week = 7 * day
if secondsAgo < minute {
return "\(secondsAgo) sec ago"
} else if secondsAgo < hour {
return "\(secondsAgo / minute) min ago"
} else if secondsAgo < day {
return "\(secondsAgo / hour) hrs ago"
} else if secondsAgo < week {
return "\(secondsAgo / day) days ago"
}
return "\(secondsAgo / week) weeks ago"
}
}
答案 0 :(得分:16)
如果您只想要Date的Time Ago扩展程序,请转到答案的底部
我将向您展示一个示例,以便在几秒钟之后以及我更新后展示您的扩展程序。
注意:如果需要,您可以直接使用Pase中的日期:
if let pastDate = (object?["createdAt"] as? Date){
cell.TimeAgo.text = pastDate.timeAgoDisplay()
}
如何使用 Swift 3 或 Swift 4 获取秒数:
第一:要获得前几秒我们需要检查我们是否有一分钟或更短时间,要获得当前日期减去一分钟,你可以写下:
let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!
第二:现在比较两个日期! (如果你的扩展我们自己替换你的日期)并获得这2个日期之间的区别。
if (minuteAgo < yourDate) {
let diff = Calendar.current.dateComponents([.second], from: yourDate, to: Date()).second ?? 0
print("\(diff) sec ago")
}
这就是全部,现在你可以打印出来了!
所以你的扩展程序是这样的: (这是一个简单的扩展,以获取时间)
extension Date {
func timeAgoDisplay() -> String {
let calendar = Calendar.current
let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!
let hourAgo = calendar.date(byAdding: .hour, value: -1, to: Date())!
let dayAgo = calendar.date(byAdding: .day, value: -1, to: Date())!
let weekAgo = calendar.date(byAdding: .day, value: -7, to: Date())!
if minuteAgo < self {
let diff = Calendar.current.dateComponents([.second], from: self, to: Date()).second ?? 0
return "\(diff) sec ago"
} else if hourAgo < self {
let diff = Calendar.current.dateComponents([.minute], from: self, to: Date()).minute ?? 0
return "\(diff) min ago"
} else if dayAgo < self {
let diff = Calendar.current.dateComponents([.hour], from: self, to: Date()).hour ?? 0
return "\(diff) hrs ago"
} else if weekAgo < self {
let diff = Calendar.current.dateComponents([.day], from: self, to: Date()).day ?? 0
return "\(diff) days ago"
}
let diff = Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear ?? 0
return "\(diff) weeks ago"
}
}
要使用它,这非常简单:
var now = Date()
now.timeAgoDisplay()
答案 1 :(得分:7)
从iOS 13开始,您可以使用Apple的RelativeDateFormatter。优点是结果字符串已本地化。
let date = Date().addingTimeInterval(-15000)
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
let string = formatter.localizedString(for: date, relativeTo: Date())
print(string) // 4 hours ago
例如参见此blog post。
答案 2 :(得分:2)
这是Swift 5中的解决方案:
extension Date {
func timeAgo() -> String {
let secondsAgo = Int(Date().timeIntervalSince(self))
let minute = 60
let hour = 60 * minute
let day = 24 * hour
let week = 7 * day
let month = 4 * week
let quotient: Int
let unit: String
if secondsAgo < minute {
quotient = secondsAgo
unit = "second"
} else if secondsAgo < hour {
quotient = secondsAgo / minute
unit = "min"
} else if secondsAgo < day {
quotient = secondsAgo / hour
unit = "hour"
} else if secondsAgo < week {
quotient = secondsAgo / day
unit = "day"
} else if secondsAgo < month {
quotient = secondsAgo / week
unit = "week"
} else {
quotient = secondsAgo / month
unit = "month"
}
return "\(quotient) \(unit)\(quotient == 1 ? "" : "s") ago"
}
}
答案 3 :(得分:1)
有点棘手)
基本上你需要
iOS提供了几种方法来实现这一目的
DateComponentsFormatter
+: 不能与本地化和其他与字符串有关的东西一起使用
-: 不太灵活
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .brief
formatter.zeroFormattingBehavior = .dropAll
let result = formatter.string(from: Date().advanced(by: -300), to: Date())
result
结果:
“ 5分钟”
RelativeDateTimeFormatter
+: 不能与本地化和其他与字符串有关的东西一起使用
-: iOS13 +
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
return formatter.localizedString(for: self, relativeTo: Date())
自定义方式
+: 灵活
-: 编写所有代码
示例:
import Foundation
public extension Date {
struct DetailedDateSuffix {
let year: String
let month: String
let week: String
let day: String
let hour: String
let min: String
let second: String
let quotient: String
let suffix: String
public init(year: String,
week: String,
month: String,
day: String,
hour: String,
min: String,
second: String,
quotient: String,
suffix: String = String.empty) {
self.year = year
self.month = month
self.week = week
self.day = day
self.hour = hour
self.min = min
self.second = second
self.quotient = quotient
self.suffix = suffix
}
}
func toDetailedReadableFormat(_ suffix: DetailedDateSuffix) -> String {
if #available(iOS 13.0, *) {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
return formatter.localizedString(for: self, relativeTo: Date())
} else {
let calendar = Calendar.current
let ageComponents = calendar.dateComponents(
[
.year,
.month,
.weekOfYear,
.day,
.hour,
.minute,
.second
],
from: self,
to: Date())
var description: String = String.empty
if let years = ageComponents.year,
let months = ageComponents.month,
let weeks = ageComponents.weekOfYear,
let days = ageComponents.day,
let hours = ageComponents.hour,
let min = ageComponents.minute,
let sec = ageComponents.second {
var requireQuotient = false
if years > 0 {
description = "\(years)" + suffix.year
requireQuotient = years == 1
} else if months > 0 {
description = "\(months)" + suffix.month
requireQuotient = months == 1
} else if weeks > 0 {
description = "\(weeks)" + suffix.week
requireQuotient = weeks == 1
} else if days > 0 {
description = "\(days)" + suffix.day
requireQuotient = days == 1
} else if hours > 0 {
description = "\(hours)" + suffix.hour
requireQuotient = hours == 1
} else if min > 0 {
description = "\(min)" + suffix.min
requireQuotient = min == 1
} else if sec > 0 {
description = "\(sec)" + suffix.second
requireQuotient = sec == 1
}
description = requireQuotient ? "\(description)\(suffix.quotient)" : description
description = "\(description)\(suffix.suffix)"
}
return description
}
}
}
答案 4 :(得分:0)
以字符串形式传递时间,例如2019-02-25 10:20:21 以可变的dateFormat传递dateformat
<script type="text/javascript">
$(document).ready(function() {
$("#sourcetable tbody tr" ).on("click", function(event) {
$("#fillname").val($(this).find("td").eq(1).html());
var j = ($(this).find("td").eq(1).html());
$("#hidfo").html(JSON.stringify(j));
$.ajax({
type: "POST",
url: 'clicktest.php',
// You don't need the parentheses for an object; might need to wrap in JSON.stringify() call
data: {prod: j},
cache: false,
success: function() {
alert("Order Submitted");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed to submit order!");
console.error(
"Failed to submit order! " + JSON.stringify(jqXHR) + "\n\t"
+ textStatus + "; " + errorThrown
);
}
});
});
});
</script>
答案 5 :(得分:0)
let now = Date()
let pastDate = Date(timeIntervalSinceNow: -60 * 60 * 24)
enum DisplayTime {
case short
case long
var seconds: String {
switch self {
case .short: return "s"
case .long: return "seconds"
}
}
var minutes: String {
switch self {
case .short: return "m"
case .long: return "minutes"
}
}
var hours: String {
switch self {
case .short: return "h"
case .long: return "hours"
}
}
var days: String {
switch self {
case .short: return "d"
case .long: return "days"
}
}
var weeks: String {
switch self {
case .short: return "w"
case .long: return "weeks"
}
}
}
extension Date {
func timeAgoDisplay(_ display: DisplayTime) -> String {
let secondsAgo = Int(Date().timeIntervalSince(self))
let minute = 60
let hour = 60 * minute
let day = 24 * hour
let week = 7 * day
switch secondsAgo {
case let seconds where seconds < minute : return "\(secondsAgo) \(display.seconds) ago"
case let seconds where seconds < hour: return "\(secondsAgo / minute) \(display.minutes) ago"
case let seconds where seconds < day: return "\(secondsAgo / hour) \(display.hours) ago"
case let seconds where seconds < week: return "\(secondsAgo / day) \(display.days) ago"
default: "\(secondsAgo / week) \(display.weeks) ago"
}
return "\(secondsAgo / week) \(display.weeks) ago"
}
}
pastDate.timeAgoDisplay(.short)
答案 6 :(得分:0)
最后在swift4.2中为我提供了一个简单的解决方案
let start = //Enter Start Date here....
let end = Date()
let formatter = DateComponentsFormatter()
formatter.maximumUnitCount = 2
formatter.unitsStyle = .full
formatter.allowedUnits = [.year, .month, .day]
let timeDifference = form.string(from: start, to: end)
print(timeDifference)
if timeDifference == "0 days"{
print("Today")
}
else if timeDifference == "1 days"{
print("\(timeDifference!)day ago")
}
else{
print("\(timeDifference!)days ago")
}
答案 7 :(得分:0)
如果只有1970年的时间戳记,则可以使用此函数返回以前的时间。
ConfigurableApplicationContext context = SpringApplication.run(DesktopAutoTradingApplication.class, args);
MarketsBinanceController marketsBinanceController = context.getBean(MarketsBinanceController.class);
marketsBinanceController.saveListOfMarketsBinance();