2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftで旧暦を扱う

Posted at

風水のアプリを作っていて旧暦を扱う必要が出てきました。
メモがてら、Swiftで旧暦を扱う方法をメモします。

Date型から算出

Date型インスタンスから旧暦を算出してみます。

Calendar(identifier: .chinese)を指定することで中国の農暦=日本でいう旧暦を指定できます。

let today = Date() //2018年12月18日に実行
// 中国の農暦 = 旧暦
let chineseCalendar = Calendar(identifier: .chinese)
let comp = chineseCalendar.dateComponents([.year, .month, .day], from: today)
print(comp.debugDescription)
// year: 35 month: 11 day: 12 isLeapMonth: false 

西暦の年月日を旧暦に変換

西暦の日付を旧暦に変換したい場合はDateComponents型を使います。

// グレゴリオ暦 = 西暦
let gregrianCalendar = Calendar(identifier: .gregorian)
var compornents = DateComponents()
compornents.year = 2018
compornents.month = 12
compornents.day = 18

// 西暦からDate型を作る
let gregrianDate = gregrianCalendar.date(from: compornents)!

// 中国の農暦 = 旧暦
let chineseCalendar = Calendar(identifier: .chinese)
// 旧暦に変換
let chineseComps = chineseCalendar.dateComponents([.year, .month, .day], from: gregrianDate)
print(chineseComps.debugDescription)

以上です。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?