LoginSignup
0
0

[Swift] DateをExcelのシリアル値に変換する方法

Last updated at Posted at 2023-02-02

数値の変換

次の変換式により、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でミリ秒までちゃんと見えてます。

スクリーンショット 2023-02-02 17.47.38.png

Excelの基準日

Excelは基準日として、デフォルトは、1899年12月31日(セル表記上は1900年1月0日)を0日とした通算日を採用している。オプション設定で、基準日を1904年に変更できる。
もし、1904年を基準日とした場合は、変換式の定数3689235430にすること。

Excelは、デフォルトの基準日の場合に1900年の閏年の判定にバグがあることが知られている
https://learn.microsoft.com/ja-jp/office/troubleshoot/excel/wrongly-assumes-1900-is-leap-year

以上

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