1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ASP.NET×Postgres】DateTime形で日時未知数の値を格納する方法

Posted at

たとえば、画面側で「yyyy-mm-dd 0:00:00」というような日時未知数な形式でサーバ側に送信した時、格納先のPostgreSQLのカラムのデータ型がtimestamp with time zoneであったときどのようにして格納すべきかを記載しておきます。

さきほどの「yyyy-mm-dd 0:00:00」の形式で送った場合に下記のエラーが発生します。

Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone', only UTC is supported.

これは、PostgreSQL のtimestamp with time zoneカラム(timestamptz)に保存するには、UTC形式の DateTime(Kind=Utc)でなければならないと Npgsql が要求しています。

解決方法(DateTime.SpecifyKind関数で変換)

DateTime.SpecifyKind関数を使えば、UTC表記に変換されテーブルへ格納することができます。

sample.cs
//例
if (book.Published.HasValue)
{
    book.Published = DateTime.SpecifyKind(book.Published.Value, DateTimeKind.Utc);
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?