Develop
2018.10.18 06:41
[ios] Swift 4 String, Date, DateFormatter 예제
조회 수 1405 댓글 0
Swift 4, Swift 3 에서 문자열을 Date() 읽고.
Date()를 DateFormatter로 문자열 출력하는 간단한 예제
1. Extensions 필요함
import Foundation
extension DateFormatter {
convenience init (format: String) {
self.init()
dateFormat = format
locale = Locale.current
}
}
extension String {
func toDate (format: String) -> Date? {
return DateFormatter(format: format).date(from: self)
}
func toDateString (inputFormat: String, outputFormat:String) -> String? {
if let date = toDate(format: inputFormat) {
return DateFormatter(format: outputFormat).string(from: date)
}
return nil
}
}
extension Date {
func toString (format:String) -> String? {
return DateFormatter(format: format).string(from: self)
}
}
2. 실행 예
var dateString = "14.01.2017T14:54:00"
let format = "dd.MM.yyyy'T'HH:mm:ss"
let date = Date()
print("original String with date: \(dateString)")
print("date String() to Date(): \(dateString.toDate(format: format)!)")
print("date String() to formated date String(): \(dateString.toDateString(inputFormat: format, outputFormat: "dd MMMM")!)")
print("format Date(): \(date.toString(format: "dd MMM HH:mm")!)")
[출처] https://stackoverflow.com/questions/24777496/how-can-i-convert-string-date-to-nsdate
번호 | 분류 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|---|
202 | System/OS | Apache CORS 설정 1 | hooni | 2020.09.04 | 2724 |
201 | System/OS | asx미디어 정보 기록.. | hooni | 2003.04.23 | 20534 |
200 | System/OS | CentOS 6.5 USB 설치 6 | hooni | 2013.12.18 | 37682 |
199 | System/OS | CentOS 에서 Cacti 설치하기 | hooni | 2015.01.02 | 1772 |
198 | System/OS | Configure Postfix to Use Gmail SMTP on Ubuntu 18.04 | hooni | 2020.02.07 | 1258 |
197 | System/OS | Enable Safari Hidden Debug Menu in Mac OS X | hooni | 2017.02.07 | 1155 |
196 | System/OS | Enable the Develop Menu in Safari | hooni | 2017.02.07 | 1081 |
195 | System/OS | How to Install and Use wget on Mac | hooni | 2020.09.03 | 1291 |
194 | System/OS | How to Setup an Email Server on CentOS 7 | hooni | 2018.04.05 | 2792 |
193 | System/OS | HTTP 프로토콜 (브라우저와 웹서버 간의 통신) | hooni | 2003.04.23 | 48253 |
192 | System/OS | HTTPS와 SSL 인증서 | hooni | 2014.03.11 | 7550 |
191 | System/OS | iptime 공유기 해킹 기술문서 4 | hooni | 2015.01.01 | 1941 |