LoginSignup
8
9

More than 3 years have passed since last update.

SwiftDate の使用方法について (2)

Last updated at Posted at 2019-11-12

基本の使用方法

1、日時解析(文字列からDate型)

1)デフォルトのフォマットから解析されるバタン:

swiftDateExample.swift
let date = "2018-12-12 10:30:00".toDate()
print("日期:", date!.date)
//実行結果:
//日期: 2018-12-12 10:30:00 +0000

(2)指定されたフォマットから解析されるパタン:

swiftDateExample.swift
let date = "2019-12-13 11:30".toDate("yyyy-MM-dd HH:mm")
print("日期:", date!.date)
//実行結果:
//日期: 2019-12-13 11:30:00 +0000

(3)通常日時フォマット(例え:ISO8601,RSS,Alt RSS,.NET,SQL,HTTP ...)などからされるパタン。
//ISO8601フォマットでの文字列から解析

swiftDateExample.swift
//ISO8601フォマットでの文字列から解析
let date1 = "2019-12-14T11:59:29+02:00".toISODate()
print("日期:", date1!.date)
//実行結果:
//日期: 2019-12-14 09:59:29 +0000

//RSSフォマットでの文字列から解析

swiftDateExample.swift
//RSSフォマットでの文字列から解析
let date2 = "15 Dec 2019 22:20:40 +0100".toRSSDate(alt: true)
print("日期:", date2!.date)
//実行結果:
//日期: 2019-12-15 21:20:40 +0000

2、DataInRegionからDateを生成(Regionはディフォルト)

1)DataInRegionの文字列フォマット、又は時間間隔、日時各コンポネートを設定することで、新しい日時を生成できます。

swiftDateExample.swift
//文字列から生成
let date1 = DateInRegion("2019-12-16 08:00:00")!
print("data1:", date1.date)
//実行結果:
//data1: 2019-12-16 08:00:00 +0000

//時間間隔を指定して生成
let date2 = DateInRegion(seconds: 39940)
let date3 = DateInRegion(milliseconds: 5000)
print("data2:", date2.date)
print("data3:", date3.date)
//実行結果:
//data2: 1970-01-01 11:05:40 +0000
//data3: 1970-01-01 00:00:05 +0000

//日時の各コンポネートを指定して生成(1)
let data4 = DateInRegion(components: {
            $0.year = 2019
            $0.month = 12
            $0.day = 17
            $0.hour = 12
            $0.minute = 0
        })
print("data4:", data4!.date)
//実行結果:
//data4: 2019-12-17 03:00:00 +0000

//日時の各コンポネートを指定して生成(2)
let date5 = DateInRegion(year: 2019, month: 12, day: 18,
                         hour: 13, minute: 30, second: 30)
print("data5:", date5.date)
//実行結果:
//data5: 2019-12-18 13:30:30 +0000

 
(2)Region(Timezone, Calendar & Locale)を指定して日時を生成
上記とほぼ同じですが、指定されたRegionをパラメタとして付与します。

swiftDateExample.swift
//Regionを初期化する
let japan = Region(calendar: Calendars.gregorian, zone: Zones.asiaTokyo, locale: Locales.japanese)
let rome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let seoul = Region(calendar: Calendars.gregorian, zone: Zones.asiaSeoul, locale: Locales.korean)

//文字列から
let date1 = DateInRegion("2019-08-08 08:00:00", region: japan)!
print("data1:", date1.date)

//从时间间隔创建
let date2 = DateInRegion(seconds: 39940, region: rome)
let date3 = DateInRegion(milliseconds: 5000, region: rome)
print("data2:", date2.date)
print("data3:", date3.date)

//日時の各コンポネートを指定して生成(1)
let data4 = DateInRegion(components: {
            $0.year = 2020
            $0.month = 1
            $0.day = 4
            $0.hour = 12
            $0.minute = 0
         }, region: seoul)
print("data4:", data4!.date)
//日時の各コンポネートを指定して生成(2)
let date5 = DateInRegion(year: 2020, month: 1, day: 5, hour: 23, minute: 30, second: 0, region: seoul)
print("data5:", date5.date)

3、日時取得

SwfitDateを利用することで、ある日時のコンポネートから必要なコンポネート(例え、年月日)等を簡単に取得できます

swiftDateExample.swift
let date = Date()
print("現在日時:", date.toString())
print("年:", date.year)
print("月:", date.month)
print("日:", date.day)
print("時:", date.hour)
print("分:", date.minute)
print("秒:", date.second)
print("最寄り時間:", date.nearestHour)
print("今月の日数:", date.monthDays)
print("今年からの何日目?:", date.dayOfYear)
print("今月名称:", date.monthName(.default))
print("今月名称(略称):", date.monthName(.veryShort))
print("今日第何曜日:", date.weekdayOrdinal)
print("今日の曜日:", date.weekday)
print("当月の週番号:", date.weekOfMonth)
print("当年の週番号:", date.weekOfYear)
print("週番号の対象年:", date.yearForWeekOfYear)
print("今日の曜日名:", date.weekdayName(.default))
print("今日の曜日名(略称):", date.weekdayName(.veryShort))
print("今週最初日は?:", date.firstDayOfWeek)
print("今週最後日は?:", date.lastDayOfWeek)
print("今日は何分期:", date.quarter)
print("現在のregion:", date.region)

//実行結果:
//現在日時: 火 11月 12 12:19:41 +0900 2019
//年: 2019
//月: 11
//日: 12
//時: 12
//分: 10
//秒: 55
//最寄り時間: 12
//今月の日数: 30
//今年からの何日目?: 316
//今月名称: 11月
//今月名称(略称): 11
//今日名称: 第12
//今日第何曜日: 2
//今日の曜日: 3
//当月の週番号: 3
//当年の週番号: 46
//週番号の対象年: 2019
//今日の曜日名: 火曜日
//今日の曜日名(略称): 火
//今週最初日は?: 10
//今週最後日は?: 16
//今日は何分期: 4
//現在のregion: {calendar='gregorian', timezone='Asia/Tokyo', locale='ja'}

4、日時指定フォマット化

(1)toFormat()メソットで指定されたフォマットの文字列を生成します。

swiftDateExample.swift
let date = "2019-12-12 10:30:00".toDate()!
//Zone 変換無し
print("現在时间:", date.toFormat("yyyy-MM-dd HH:mm:ss"))
//香港時間に変換して表示
print("香港时间:", date.convertTo(timezone: Zones.asiaHongKong).toFormat("yyyy-MM-dd HH:mm:ss"))

//実行結果:
//現在时间: 2019-12-12 10:30:00
//香港时间: 2019-12-12 09:30:00

(2)相対的な時間(5分前とか、1時間後等)を簡単に計算し生成します。

swiftDateExample.swift
let r1 = (Date() - 2.years).toRelative(style: RelativeFormatter.defaultStyle()) //2年前
let r2 = (Date() - 10.months).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //10 か月前
let r3 = (Date() - 3.weeks).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //3 週間前
let r4 = (Date() - 5.days).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //5 日前
let r5 = (Date() - 12.hours).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //12 時間前
let r6 = (Date() - 30.minutes).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //30 分前
let r7 = (Date() - 30.seconds).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //今
let r8 = (Date() + 30.seconds).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //今
let r9 = (Date() + 30.minutes).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //30 分後
let r10 = (Date() + 12.hours).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //12 時間後
let r11 = (Date() + 5.days).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //5 日後
let r12 = (Date() + 3.weeks).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //3 週間後
let r13 = (Date() + 10.months).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //10 か月後
let r14 = (Date() + 2.years).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.japanese) //2 年後

(3).toClock()メソットを利用することで、TimeIntervalを"時:分:秒"フォマットの文字列で表示できます。

swiftDateExample.swift
let interval: TimeInterval = 2.hours.timeInterval + 30.minutes.timeInterval + 15.seconds.timeInterval
print("カウントダウン:", interval.toClock())

//実行結果:
//カウントダウン: 02:30:15

5、閏年、閏月の判断を簡単にする

swiftDateExample.swift
let date1 = "2019-02-12 10:30:00".toDate()!.date
print(date1.toFormat("yyyy年MM月dd日"), "は閏年ですか:", date1.isLeapYear ? "はい" : "いいえ")
print(date1.toFormat("yyyy年MM月dd日"), "は閏月ですか:", date1.isLeapMonth ? "はい" : "いいえ")

let date2 = "2020-02-12 10:30:00".toDate()!.date
print(date2.toFormat("yyyy年MM月dd日"), "は閏年ですか:", date2.isLeapYear ? "はい" : "いいえ")
        print(date2.toFormat("yyyy年MM月dd日"), "は閏月ですか:", date2.isLeapMonth ? "はい" : "いいえ")

//実行結果:
//2019年02月12日 は閏年ですか: いいえ
//2019年02月12日 は閏月ですか: いいえ
//2020年02月12日 は閏年ですか: はい
//2020年02月12日 は閏月ですか: はい

6、Codableプロトーコルへの対応

swiftDateのDateInRegionとRegionはSwiftのCodableプロトコルをサポートするので、簡単にこれらをencode、decode操作を行うことができます。

无论是 DateInRegion 还是 Region 都是完全支持 Swift 的 Codable 协议,这就意味着我们可以方便安全地对它们进行 encode 和 decode 操作。

swiftDateExample.swift
print("Regionをencode, decodeする:")
let region = Region(calendar: Calendars.gregorian, zone: Zones.asiaTokyo, locale: Locales.japanese)
let encodedJSON = try! JSONEncoder().encode(region)
print("encoded: ", encodedJSON)
let decodedRegion = try! JSONDecoder().decode(Region.self, from: encodedJSON)
print("decoded: ", decodedRegion)
print("\n")

print("DateInRegionをencode, decodeする:")
let date = DateInRegion("2020-01-24T13:20:55", region: region)
let encodedDate = try! JSONEncoder().encode(date)
print("encoded: ", encodedDate)
let decodedDate = try! JSONDecoder().decode(DateInRegion.self, from: encodedDate)
print("decoded: ", decodedDate)
print("\n")

//実行結果:
//Regionをencode, decodeする:
//encoded:  63 bytes
//decoded:  {calendar='gregorian', timezone='Asia/Tokyo', locale='ja'}
//
//DateInRegionをencode, decodeする:
//encoded:  91 bytes
//decoded:  {abs_date='2020-01-24T04:20:55Z', rep_date='2020-01-24T13:20:55+09:00', region=//{calendar='gregorian', timezone='Asia/Tokyo', locale='ja'}

ここまで、SwiftDateの簡単な使用方法について、纏めてみました。
次回はSwiftDateの計算方法や拡張機能について少し説明しようと思います。

iOS、Androidアプリの制作なら、https://origon.co.jp にお任せください
信頼且つ満足できる製品を納品いたします

  • SwiftDate の使用方法について(1) 前の記事を読む

  • SwiftDate の使用方法について(3) [次の記事を読む(準備中)]

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9