数値の変換
次の変換式により、SwiftのDate型の値をExcelのシリアル値に変換する。
let dateTime: Date = xxxx
let serialValueForExcel = (dateTime.timeIntervalSinceReferenceDate / 86400) + 36892 + 0.375
- 86400:1日=24時間=24×60×60=86400秒
- 36892:1899年12月31日から2001年1月1日までの日数
- 0.375:9×60×60/86400:日本の時差(UTC+9時間)
※)なお、dateTimeは2001年以降の日付であること Excelの基準日以降の日付であればいつでも可
例
let now = Date()
//2023.02.02(木)17:44:05.917
print(now.timeIntervalSinceReferenceDate)
//697020245.917199
let serialValueForExcel = (now.timeIntervalSinceReferenceDate / 86400) + 36892 + 0.375
print(serialValueForExcel)
//44959.73895737499
↓Excelでミリ秒までちゃんと見えてます。
Excelの基準日
Excelは基準日として、デフォルトは、1899年12月31日(セル表記上は1900年1月0日)を0日とした通算日を採用している。オプション設定で、基準日を1904年に変更できる。
もし、1904年を基準日とした場合は、変換式の定数36892
を35430
にすること。
Excelは、デフォルトの基準日の場合に1900年の閏年の判定にバグがあることが知られている
https://learn.microsoft.com/ja-jp/office/troubleshoot/excel/wrongly-assumes-1900-is-leap-year
以上