1
let date1 = "2017-02-09 11:51:07"
let date2 = **I need now time code**
スウィフト3で日付を計算するには? がどのようにこれを計算する方法
誰もが私を助けてください "1日前"、 "1時間前"、 "10分前" のように見える〜
let date1 = "2017-02-09 11:51:07"
let date2 = **I need now time code**
スウィフト3で日付を計算するには? がどのようにこれを計算する方法
誰もが私を助けてください "1日前"、 "1時間前"、 "10分前" のように見える〜
は、DateFormatter
、この遊び場Date
を使用
//: Playground - noun: a place where people can play
import Cocoa
// Given a date as a string
let dateString = "2017-02-09 11:51:07"
// To turn it into a date we can use a date formatter
let dateFormatter = DateFormatter()
// Make sure the formatter is using the correct format for your date string
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
// Attempt to create a date from the string using our date formatter
guard let date = dateFormatter.date(from: dateString) else {
fatalError("Unable to create date from string \(dateString) with format \(dateFormatter.dateFormat)")
}
// Calendar can do all kinds of things with dates
let calendar = Calendar(identifier: .gregorian)
// Date() By itself will give us "now" date
let now = Date()
// We can ask the calendar to give us the hours and minutes between now and the date we parsed
let components = calendar.dateComponents([.hour, .minute], from: date, to: now)
// If getting the hours was succesful we can use them
if let hours = components.hour {
print("\(hours) hours ago")
}
// same with minutes
if let minutes = components.minute {
print("\(minutes) minutes ago")
}
// you can also try using DateComponentsFormatter
let componentsFormatter = DateComponentsFormatter()
componentsFormatter.allowedUnits = [.day, .minute, .hour]
componentsFormatter.maximumUnitCount = 2
componentsFormatter.unitsStyle = .full
if let fromString = componentsFormatter.string(from: date, to: now) {
print("Parsed date was \(fromString) ago.")
}
をチェックCalendar
、DateComponentsFormatter
、およびDateComponents
APIは、あなたはこれをやってのけることができるはずです。
'は、hh:mmの:ss'が間違っています。 hhは01-12を意味します。それはHH(00-23)でなければなりません。 –
彼が 'HH'フォーマットを使用しているとすれば、あなたは正しいです!彼は質問に「11」を使用しているので、データをもっと与えなければ、本当に必要なフォーマットはあいまいです! –
曖昧でないAM PM情報はありません。あなたは 'HH:mm:ss'を使う必要があります。 –