Develop
2018.10.18 06:41
[ios] Swift 4 String, Date, DateFormatter 예제
Views 1520 Comment 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
No. | Category | Subject | Author | Date | Views |
---|---|---|---|---|---|
57 | Develop |
[api] 인스타그램 API Access_Token 발급 방법 (Instagram API)
3 ![]() |
hooni | 2018.04.05 | 7760 |
56 | Develop |
[php] Connect to Firebase Console in Laravel
![]() |
hooni | 2018.05.09 | 3234 |
55 | Develop |
[PHP] MacOS에서 PHP 7 설치하기
![]() |
hooni | 2018.05.11 | 5056 |
54 | Develop |
[ios] Requesting Location Permissions in iOS
![]() |
hooni | 2018.08.18 | 1744 |
53 | System/OS |
서버 확장을 위한 두 가지 방법
![]() |
hooni | 2018.08.29 | 2278 |
52 | System/OS |
Mac에서 Node.js 설치하기
![]() |
hooni | 2018.09.28 | 4346 |
» | Develop | [ios] Swift 4 String, Date, DateFormatter 예제 | hooni | 2018.10.18 | 1520 |
50 | Develop | [ios] APNS, Remote Push 수신 시점에서 앱의 3가지 실행 상태 | hooni | 2018.10.19 | 1100 |
49 | Develop | [ios] APNS, Remote Push 사용자가 수신을 동의했는지 확인하기 | hooni | 2018.10.19 | 1377 |
48 | Develop | [ios] Swift 4 Singleton inheritance | hooni | 2018.10.31 | 1695 |
47 | Develop |
[ios] Swift 4 Dictionary 사용하기
![]() |
hooni | 2018.11.29 | 2133 |
46 | Develop |
[ios] Locale Identifiers
![]() |
hooni | 2018.11.29 | 1747 |