Created
December 21, 2020 11:39
-
-
Save sugimomoto/7d13c6a581b1eabead1f2f46da260fa3 to your computer and use it in GitHub Desktop.
Datetime Formatter for Swift
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
import UIKit | |
/* | |
Date型から任意のフォーマットで文字列を生成する場合 | |
*/ | |
// Reference | |
// https://developer.apple.com/documentation/foundation/dateformatter | |
var date = Date() | |
// 2020-12-20 06:03:36 +0000 | |
// 組み込みテンプレートを使いたい場合 | |
// 各言語設定からフォーマットを呼び出すことが可能 | |
/* | |
値 日本語での例 英語での例 | |
.full 2019年6月27日 木曜日 Thursday, June 27, 2019 | |
.long 2019年6月27日 June 27, 2019 | |
.medium 2019/06/27 Jun 27, 2019 | |
.short 2019/06/27 6/27/19 | |
.none 表示なし 表示なし | |
*/ | |
var formatter = DateFormatter() | |
formatter.locale = Locale(identifier: "ja_JP") | |
formatter.dateStyle = .full | |
formatter.timeStyle = .full | |
print(formatter.string(from: date)) | |
// 2020年12月20日 日曜日 15時15分48秒 日本標準時 | |
formatter.dateStyle = .medium | |
formatter.timeStyle = .none | |
print(formatter.string(from: date)) | |
// 2020/12/20 | |
// 独自フォーマットを記述する場合 | |
// Templateを自分自身で定義して呼び出すことが可能 | |
formatter = DateFormatter() | |
formatter.setLocalizedDateFormatFromTemplate("yyyy/MM/dd hh:mm:ss") | |
print(formatter.string(from: date)) | |
/* | |
現在日時・昨日・今日の時間の求め方 | |
現在時刻からの相対値として求める場合、Date.addingTimeIntervalを使って、秒単位の時間を加算、もしくは減算することで求めることができる。 | |
https://developer.apple.com/documentation/foundation/date/1948745-addingtimeinterval | |
*/ | |
let now = Date() | |
let dayOfSeconds:Double = 60 * 60 * 24 | |
let tomorrow = now.addingTimeInterval(dayOfSeconds) | |
let yesterday = now.addingTimeInterval(dayOfSeconds * -1) | |
var jpFormat = DateFormatter() | |
jpFormat.locale = Locale(identifier: "ja_JP") | |
jpFormat.dateStyle = .full | |
jpFormat.timeStyle = .full | |
print(jpFormat.string(from: now)) | |
// 2020年12月20日 日曜日 15時38分12秒 日本標準時 | |
print(jpFormat.string(from: tomorrow)) | |
// 2020年12月21日 月曜日 15時38分12秒 日本標準時 | |
print(jpFormat.string(from: yesterday)) | |
// 2020年12月19日 土曜日 15時38分12秒 日本標準時 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment