Created
February 13, 2017 18:41
-
-
Save runys/5c537075323abe0093a21cb8e7b2d505 to your computer and use it in GitHub Desktop.
Ways to work with date and time in iOS 10 and Swift 3.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. Como transformar Date em String? | |
let today = Date() | |
// 1: Criamos um NSDateFormatter | |
let dateFormatter = DateFormatter() | |
// 2: Definimos o formato da data | |
dateFormatter.dateFormat = "EEE, dd MMM yyy hh:mm:ss +zzzz" | |
// 3: Criamos uma string atravéz da data | |
dateFormatter.string(from: today) | |
// Outros exemplos de formatos | |
dateFormatter.dateFormat = "MM-dd-yyyy" | |
dateFormatter.dateFormat = "MM/dd/yy" | |
dateFormatter.dateFormat = "hh:mm:ss" | |
dateFormatter.dateFormat = "EEE, dd MMM yyy" | |
// Um exemplo usando uma função | |
func stringFromDate(date: Date, with format: String) -> String { | |
let dateFormatter = DateFormatter() | |
dateFormatter.dateFormat = format | |
return dateFormatter.string(from: date) | |
} | |
// 2. Como gerar um Date a partir de String? | |
func date(for hour: Int, and minute: Int) -> Date? { | |
// 1: Acessamos o calendário | |
let calendar = Calendar.current | |
// 2: Pegamos a data e hora atuais | |
let currentDate = Date() | |
// 3: Pegamos os componentes da data que nos interessam | |
var dateComponents = calendar.dateComponents([.minute, .hour, .day, .month, .year], from: currentDate) | |
// 4: Alteramos a hora para a hroa solicitada | |
dateComponents.hour = hour | |
dateComponents.minute = minute | |
// 5: Criamos um novo objeto Date a partir dos componentes que possuímos | |
let date = calendar.date(from: dateComponents) | |
return date | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment