2017-02-10 4 views
1
let date1 = "2017-02-09 11:51:07" 
let date2 = **I need now time code** 

Как рассчитать это? выглядит "10 минут назад", "1 день назад", "1 день назад"Как рассчитать дату в Swift 3

кто-нибудь поможет мне, пожалуйста ~

ответ

1

Проверить эту площадку

//: 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.") 
} 

Использование Date, DateFormatter, Calendar, DateComponentsFormatter и DateComponents API вы сможете убрать это.

+2

'hh: mm: ss' неверно. hh означает 01-12. Он должен быть HH (00-23). –

+0

Предполагая, что он использует формат 'HH', вы правы! Он использовал '11' в своем вопросе, поэтому он неоднозначен, какой формат ему действительно нужен, если он не дает больше данных! –

+1

не двусмысленный нет информации AM PM. Вам нужно использовать 'HH: mm: ss' –

Смежные вопросы