C#在功能数据集中将UTC转换为本地时间

时间:2012-07-23 13:39:49

标签: c# sql datetime dataset

我需要一个帮助来改变我的方法的形式填充我的数据库。

我使用API​​通过OPC协议与工业设备进行通信。

此API将参数作为通用时区(UTC),但我在光栅(UTC)中的差异为+3小时。

在我的数据集中,我将此API用于一个返回三个属性的类:数据值,质量和时间戳

我需要转换为本地时间,以便在我的数据库中保存此属性Timestamp。

遵循我的班级的一个类示例。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using OpcLabs.EasyOpc.DataAccess;

namespace LogAsStringToSql
{
    class Program
    {
        static void Main()
        {
            const string connectionString =
                "Data Source=.\\SQLEXPRESS;Initial Catalog=QuickOPCExamples;Integrated Security=true";

            Console.WriteLine("Starting up...");
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();

                // Create all necessary ADO.NET objects.
                var adapter = new SqlDataAdapter("SELECT * FROM SimpleLog", connection);
                var dataSet = new DataSet();
                adapter.FillSchema(dataSet, SchemaType.Source, "SimpleLog");
                adapter.InsertCommand = new SqlCommandBuilder(adapter).GetInsertCommand();
                DataTable table = dataSet.Tables["SimpleLog"];

                Console.WriteLine("Logging for 30 seconds...");
                // Subscribe to an OPC item, using an anonymous method to process the notifications.
                int[] handles = EasyDAClient.DefaultInstance.SubscribeMultipleItems(
                    new[]
                        {
                            new DAItemGroupArguments("", "OPCLabs.KitServer.2", "Simulation.Incrementing (1 s)", 100, null),
                            new DAItemGroupArguments("", "OPCLabs.KitServer.2", "Simulation.Ramp (10 s)", 1000, null),
                            new DAItemGroupArguments("", "OPCLabs.KitServer.2", "Simulation.Register_BSTR", 1000, null),
                            new DAItemGroupArguments("", "OPCLabs.KitServer.2", "Simulation.Register_BOOL", 1000, null)
                        },
                    (_, eventArgs) =>
                    {
                        Console.Write(".");
                        // In this example, we only log valid data. Production logger would also log errors.
                        if (eventArgs.Vtq != null)
                        {
                            // Fill a DataRow with the OPC data, and add it to a DataTable.
                            table.Rows.Clear();
                            DataRow row = table.NewRow();
                            row["ItemID"] = eventArgs.ItemDescriptor.ItemId;
                            row["Value"] = eventArgs.Vtq.Value; // The DataRow will make the conversion to a string.
                            row["Timestamp"] = (eventArgs.Vtq.Timestamp < (DateTime)SqlDateTime.MinValue)
                                                   ? (DateTime)SqlDateTime.MinValue
                                                   : eventArgs.Vtq.Timestamp;
                            row["Quality"] = (short)eventArgs.Vtq.Quality;
                            table.Rows.Add(row);

                            // Update the underlying DataSet using an insert command.
                            adapter.Update(dataSet, "SimpleLog");
                        }
                    }
                    );
                System.Threading.Thread.Sleep(60 * 1000);
                Console.WriteLine();

                Console.WriteLine("Shutting down...");
                EasyDAClient.DefaultInstance.UnsubscribeMultipleItems(handles);
            }

            Console.WriteLine("Finished.");
        }
    }
}

如何更改当前方法以在DateTime上使用ToLocalTime()方法来接收localtime中的时间戳?

row["Timestamp"] = (eventArgs.Vtq.Timestamp < (DateTime)SqlDateTime.MinValue)
                                                   ? (DateTime)SqlDateTime.MinValue
                                                   : eventArgs.Vtq.Timestamp;

我无法理解如何改变这一点,非常欢迎任何帮助。

1 个答案:

答案 0 :(得分:1)

是不是就像下面一样?

row["Timestamp"] = (eventArgs.Vtq.Timestamp < (DateTime)SqlDateTime.MinValue)
                                                   ? (DateTime)SqlDateTime.MinValue
                                                   : eventArgs.Vtq.Timestamp.ToLocalTime();

上面的代码只能确保您不会尝试将过时的日期保存到数据库中,这会引发异常。如果不是这种情况,您可以将转换日期保存为当地时间。见?: operator

可能是我误解了你的问题。