본문 바로가기

프로그래밍 언어/Swift

[Swift] 현재 날짜 및 시간 출력하기 Date(), DateFormatter()

반응형
Date()

현재 날짜 및 시간을 알려주는 Date()

print(Date())

 

2019-07-05 08:11:58 +0000

Date()를 출력하면 다음과 같이 날짜와 시간이 출력됩니다. 

 

 

DateFormatter()

"연도만 출력하고 싶다" 또는 "시간만 알고 싶다"와 같이 특정 값만 출력하고 싶을 경우 DateFormatter()를 통해 원하는 값을 얻을 수 있습니다.

 

var formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var current_date_string = formatter.string(from: Date())
print(current_date_string)
2019-07-05 17:25:18
var formatter_year = DateFormatter()
formatter_year.dateFormat = "yyyy"
var current_year_string = formatter_year.string(from: Date())
print(current_year_string)
2019
var formatter_time = DateFormatter()
formatter_time.dateFormat = "HH:mm"
var current_time_string = formatter_time.string(from: Date())
print(current_time_string)
17:25

 

 

 

반응형

'프로그래밍 언어 > Swift' 카테고리의 다른 글

[Swift] 전처리 매크로  (0) 2020.04.16
[Swift] 윤년 계산기  (0) 2019.07.05
[Swift] 함수 Function  (0) 2019.07.04
[Swift] 튜플 tuple  (0) 2019.07.04
[Swift] 베이스볼 게임  (0) 2019.07.02