Develop
2018.10.18 06:41
[ios] Swift 4 String, Date, DateFormatter 예제
Views 1521 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 |
---|---|---|---|---|---|
481 | Develop | [ios] UIAlertView 초간단 샘플 ㅎㅎ | hooni | 2013.10.14 | 46208 |
480 | Develop |
[ios] UDID와 UUID (디바이스의 Unique Identifier)
![]() |
hooni | 2013.04.23 | 27407 |
479 | Develop | [ios] UDID 사용 제한에 따른 대안들 | hooni | 2014.03.13 | 4025 |
478 | Develop |
[ios] Touch ID 적용 샘플 코드 (예제)
![]() |
hooni | 2015.02.23 | 769 |
477 | Develop | [ios] Thread Loop 내에서 UI 업데이트 방법 | hooni | 2015.01.03 | 929 |
476 | Develop | [ios] TextField 특정 문자만 사용하도록 하기 | hooni | 2014.06.30 | 2797 |
» | Develop | [ios] Swift 4 String, Date, DateFormatter 예제 | hooni | 2018.10.18 | 1521 |
474 | Develop | [ios] Swift 4 Singleton inheritance | hooni | 2018.10.31 | 1696 |
473 | Develop |
[ios] Swift 4 Dictionary 사용하기
![]() |
hooni | 2018.11.29 | 2135 |
472 | Develop |
[ios] StoryBoard(xib) 없이 프로젝트 만들기
![]() |
hooni | 2015.02.12 | 1165 |
471 | Develop |
[ios] Start developing your navigation app for CarPlay without enrollment
![]() |
hooni | 2020.02.22 | 125610 |
470 | Develop |
[ios] SQLite 사용하기(튜토리얼) + 샘플코드
![]() |
hooni | 2014.03.28 | 3755 |