我需要帮助来更改填充数据库的方法的形式。
我使用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()方法来接收本地时间的时间戳?
row["Timestamp"] = (eventArgs.Vtq.Timestamp < (DateTime)SqlDateTime.MinValue)
? (DateTime)SqlDateTime.MinValue
: eventArgs.Vtq.Timestamp;
我很难理解如何改变这一点,欢迎提供任何帮助,谢谢。
它不是如下所示吗?
row["Timestamp"] = (eventArgs.Vtq.Timestamp < (DateTime)SqlDateTime.MinValue)
? (DateTime)SqlDateTime.MinValue
: eventArgs.Vtq.Timestamp.ToLocalTime();
上面的代码只确保您不会试图将太旧的日期保存到数据库中,这会引发异常。如果不是这样,您可以保存转换为当地时间的日期。看到了吗?:操作员
可能是我误解了你的问题。