nsdate - tiempo - contador de dias horas minutos y segundos
Swift 3-encuentra el número de días calendario entre dos fechas (9)
La forma en que hice esto en Swift 2.3 fue:
let currentDate = NSDate()
let currentCalendar = NSCalendar.currentCalendar()
var startDate : NSDate?
var endDate : NSDate?
// The following two lines set the `startDate` and `endDate` to the start of the day
currentCalendar.rangeOfUnit(.Day, startDate: &startDate, interval: nil, forDate: currentDate)
currentCalendar.rangeOfUnit(.Day, startDate: &endDate, interval: nil, forDate: self)
let intervalComps = currentCalendar.components([.Day], fromDate: startDate!, toDate: endDate!, options: [])
print(intervalComps.day)
Ahora todo esto ha cambiado con Swift 3. Tengo que usar NSCalendar
y NSDate
al escribir constantemente casting con as
, o encontrar la forma Swift 3 de hacerlo.
¿Cuál es la forma correcta de hacerlo en Swift 3?
Actualizado para Swift 3:
si desea imprimir la cantidad de días y la lista de días entre dos fechas de calendario, utilice el código simple a continuación;
// Declaración Variable:
var daysListArray = [String]()
// Definición de la función:
func printCountBtnTwoDates(mStartDate: Date, mEndDate: Date) -> Int {
let calendar = Calendar.current
let formatter = DateFormatter()
var newDate = mStartDate
daysListArray.removeAll()
while newDate <= mEndDate {
formatter.dateFormat = "yyyy-MM-dd"
daysListArray.append(formatter.string(from: newDate))
newDate = calendar.date(byAdding: .day, value: 1, to: newDate)!
}
// print("daysListArray: /(daysListArray)") // if you want to print list between start date and end date
return daysListArray.count
}
// Para llamar a la función anterior:
let count = self.printCountBtnTwoDates(mStartDate: your_start_date, mEndDate: your_end_date)
print("count: /(count)") // date count
// ¡Disfruta de la codificación ...!
En Swift 4 hay una línea simple para obtener el número de días (o cualquier otro DateComponent) entre dos fechas:
let diffInDays = Calendar.current.dateComponents([.day], from: dateA, to: dateB).day
En Swift4 podemos obtener fácilmente el número de días entre dos fechas de calendario diferentes utilizando los códigos que se muestran a continuación.
El primero es la diferencia en días con la fecha actual.
let previousDate = "2017-03-01"
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let previousDateFormated : Date? = dateFormatter.date(from: previousDate)
let difference = currentDate.timeIntervalSince(previousDateFormated!)
var differenceInDays = Int(difference/(60 * 60 * 24 ))
print(differenceInDays)
Continuando con el código anterior ... A continuación se muestra el número de días para dos fechas diferentes. El contenido de la fecha anterior se toma de la fecha anterior.
let futureDate = "2017-12-30"
let futureDateFormatted : Date? = dateFormatter.date(from: futureDate)
differenceInDays = (futureDateFormatted?.timeIntervalSince(previousDateFormated!))! / (60 * 60 * 24)
print(differenceInDays)
Encontré esto en un hilo diferente, pero finalmente fue la solución más simple para mí usando Swift 4:
let previousDate = ENTER DATE HERE
let now = Date()
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .brief // May delete the word brief to let Xcode show you the other options
formatter.allowedUnits = [.month, .day, .hour]
formatter.maximumUnitCount = 1 // Show just one unit (i.e. 1d vs. 1d 6hrs)
let stringDate = formatter.string(from: previousDate, to: now)
Resulta que esto es mucho más simple de hacer en Swift 3:
extension Date {
func interval(ofComponent comp: Calendar.Component, fromDate date: Date) -> Int {
let currentCalendar = Calendar.current
guard let start = currentCalendar.ordinality(of: comp, in: .era, for: date) else { return 0 }
guard let end = currentCalendar.ordinality(of: comp, in: .era, for: self) else { return 0 }
return end - start
}
}
Editar
La comparación de la ordinalidad de las dos fechas debe estar dentro de la misma era
lugar del mismo year
, ya que, naturalmente, las dos fechas pueden caer en años diferentes.
Uso
let yesterday = Date(timeInterval: -86400, since: Date())
let tomorrow = Date(timeInterval: 86400, since: Date())
let diff = tomorrow.interval(ofComponent: .day, fromDate: yesterday)
// return 2
Si alguien quiere hacerlo más específicamente siga los siguientes pasos
1.Agregue esta extensión de fecha
extension Date {
/// Returns the amount of years from another date
func years(from date: Date) -> Int {
return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0
}
/// Returns the amount of months from another date
func months(from date: Date) -> Int {
return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
}
/// Returns the amount of weeks from another date
func weeks(from date: Date) -> Int {
return Calendar.current.dateComponents([.weekOfMonth], from: date, to: self).weekOfMonth ?? 0
}
/// Returns the amount of days from another date
func days(from date: Date) -> Int {
return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
}
/// Returns the amount of hours from another date
func hours(from date: Date) -> Int {
return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
}
/// Returns the amount of minutes from another date
func minutes(from date: Date) -> Int {
return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
}
/// Returns the amount of seconds from another date
func seconds(from date: Date) -> Int {
return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
}
/// Returns the amount of nanoseconds from another date
func nanoseconds(from date: Date) -> Int {
return Calendar.current.dateComponents([.nanosecond], from: date, to: self).nanosecond ?? 0
}
/// Returns the a custom time interval description from another date
func offset(from date: Date) -> String {
var result: String = ""
if years(from: date) > 0 { return "/(years(from: date))y" }
if months(from: date) > 0 { return "/(months(from: date))M" }
if weeks(from: date) > 0 { return "/(weeks(from: date))w" }
if seconds(from: date) > 0 { return "/(seconds(from: date))" }
if days(from: date) > 0 { result = result + " " + "/(days(from: date)) D" }
if hours(from: date) > 0 { result = result + " " + "/(hours(from: date)) H" }
if minutes(from: date) > 0 { result = result + " " + "/(minutes(from: date)) M" }
if seconds(from: date) > 0 { return "/(seconds(from: date))" }
return ""
}
}
2.Defínelo en global
fileprivate var timer: Timer?
3.Llama este método en viewDidLoad o donde quieras
override func viewDidLoad() {
super.viewDidLoad()
self.getRemainingTime()
}
4.Uso
fileprivate func getRemainingTime() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let startDate = "2018-06-02 10:11:12"
let currentDate = dateFormatter.string(from: Date())
if currentDate != startDate {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(calculateTime)), userInfo: nil, repeats: true)
RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes)
timer?.fire()
}
else {
self.timer?.invalidate()
self.timer = nil
}
}
func calculateTime() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let stdate : String = "2018-06-02 10:11:12"
let startDate = dateFormatter.date(from: stdate)!
let currentDate = Date()
let strTimer : String = startDate.offset(from: currentDate)
if !strTimer.isEmpty {
let stDay: String = "/((Int(strTimer)! % 31536000) / 86400)"
let stHour: String = "/((Int(strTimer)! % 86400) / 3600)"
let stMin: String = "/((Int(strTimer)! % 3600) / 60)"
let stSec: String = "/(Int(strTimer)! % 60)"
yourLabelOutlet.text = "Start In :/(stDay) Days /(stHour) Hours /(stMin) Minutes /(stSec) Seconds"
}
}
Funciona como Charm. Puedes usar cada cadena por separado para tu lado UI, disfruta
Versión Swift 4
let startDate = "2000-11-22"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let formatedStartDate = dateFormatter.date(from: startDate)
let currentDate = Date()
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .month, .year])
let differenceOfDate = Calendar.current.dateComponents(components, from: formatedStartDate!, to: currentDate)
print (differenceOfDate)
Impreso - año: 16 meses: 10 días: 19 horas: 12 minutos: 16 segundos: 42 isLeapMonth: false
date calendar swift4
private func calculateDaysBetweenTwoDates(start: Date, end: Date) -> Int {
let currentCalendar = Calendar.current
guard let start = currentCalendar.ordinality(of: .day, in: .era, for: start) else {
return 0
}
guard let end = currentCalendar.ordinality(of: .day, in: .era, for: end) else {
return 0
}
return end - start
}
private func days(actual day1:[Int],expect day2:[Int]) -> Int {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let first = "/(day1[2])-/(day1[1])-/(day1[0])"
let firstDate = dateFormatter.date(from:first)!
let last = "/(day2[2])-/(day2[1])-/(day2[0])"
let lastDate = dateFormatter.date(from:last)!
let currentCalendar = NSCalendar.current
let components = currentCalendar.dateComponents([.day], from: firstDate, to: lastDate)
return components.day!
}
Otro enfoque para comparar con componentes de día mes año
Uso:
Ingrese las fechas en el siguiente formato
[dd, mm, yyyy]
[9, 6, 2017]
[6, 6, 2017]