简体   繁体   English

C#:当插入到 DateTimeOffset SQL 服务器列时,如何停止将时区偏移添加到 System.DateTime

[英]C# : how to stop timezone offset being added to System.DateTime when inserted into a DateTimeOffset SQL Server column

I have some C# code that copies rows from one database and inserts them into another.我有一些 C# 代码从一个数据库复制行并将它们插入另一个数据库。 It does this using a DataTable and SqlBulkCopy .它使用DataTableSqlBulkCopy来做到这一点。

When imported into my C# application, the timestamp columns have the data type System.DateTime inside the DataTable that is inserted into SQL Server.当导入我的 C# 应用程序时,时间戳列在插入到 SQL 服务器的DataTable中具有数据类型System.DateTime Once SqlBulkCopy.WriteToServer() has executed, timestamp values inside the destination tables have the type datetimeoffset(6) and have a timezone offset added to them (... +01:00).执行SqlBulkCopy.WriteToServer()后,目标表中的时间戳值的类型为datetimeoffset(6)并添加了时区偏移量 (... +01:00)。

How do I stop this happening?我该如何阻止这种情况发生? It hasn't always happened, only started happening recently.它并不总是发生,只是最近才开始发生。

UPDATE:更新:

The timezone expected is UTC, always, for my purposes.出于我的目的,预期的时区始终是 UTC。 However, I am forced to store this in a datetimeoffset column for business reasons.但是,出于商业原因,我被迫将其存储在 datetimeoffset 列中。 So I'm expecting +00:00所以我期待 +00:00

DataTable data = importer.GetDataTable();

using (SqlBulkCopy copy = new SqlBulkCopy(conn)){
   copy.WriteToServer(data);
}

If you have a DateTime and try to write it to a DateTimeOffset C# has to figure out what timezone to use.如果您有DateTime并尝试将其写入DateTimeOffset C# 必须弄清楚要使用的时区。 There are explicit conversion functions that allow you to specify but if you don't it will assume the DateTime is in the local timezone (as the majority of the time they are).有允许您指定的显式转换函数,但如果您不指定,它将假定DateTime位于本地时区(大部分时间都是如此)。

https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-datetime-and-offset provides several examples on how to convert between the two. https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-datetime-and-offset提供了几个关于如何在两者之间转换的示例。 Note that SpecifyKind doesn't require having a DateTimeOffset type.请注意, SpecifyKind不需要DateTimeOffset类型。

Using DateTime.SpecifyKind() on timestamp columns before inserting them into Sql Server didn't work for me.在将时间戳列插入 Sql 服务器之前在时间戳列上使用 DateTime.SpecifyKind() 对我不起作用。

I solved this by converting (casting) the System.DateTime columns to DateTimeOffset with an explicit offset of new TimeSpan(0, 0, 0) .我通过使用new TimeSpan(0, 0, 0)的显式偏移将System.DateTime列转换(转换)为DateTimeOffset解决了这个问题。 This removed the need for C# to implicitly handle the conversion from DateTime to DbType.DateTimeOffset which was adding an undesired offset.这消除了 C# 隐式处理从DateTimeDbType.DateTimeOffset的转换的需要,这增加了一个不需要的偏移量。

EDIT编辑

Reading the comments, @JohnSkeet essentially recommended this but I hadn't read everyone's comments.阅读评论,@JohnSkeet 基本上推荐了这个,但我没有阅读每个人的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM