日本語
English
How to Convert a PLC DATE_AND_TIME to a C# DateTime
Overview
The PLC NX series represents time as the elapsed time since 1970-01-01 00:00:00 counted in 1 ns units
Windows represents time as the elapsed time since 1601-01-01 00:00:00 counted in 100 ns units
| NX/NJ | Windows | |
|---|---|---|
| Start time | 1970-01-01 (Unix epoch) | 1601-01-01 (NT time epoch) |
| Interval | 1ns | 100ns |
This page shows how to convert PLC time data read as a byte array, using C#
| Description | NX/NJ | Windows |
|---|---|---|
| Date | DATE | DateTime |
| Date/time | DATE_AND_TIME | DateTime |
| Elapsed time | TIME | TimeSpan |
| Time of day | TIME_OF_DAY | TimeSpan |
DATE and DATE_AND_TIME types
Convert to DateTime using DateTime.AddTicks
Divide the value (count) of the Unix time variable by 100
and add it to the Windows count for 1970-01-01 00:00:00 to get the Windows time variable
private static DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, 0);
// Read a structure containing a DATE_AND_TIME on the PLC into a byte array with Compolet (example: Compolet)
byte[] value = compolet1.ReadValiable("struct1");
// Convert the DATE_AND_TIME bytes in the byte array to an INT64 and convert 1 ns units to 100 ns units
// Set it in Val as the elapsed time from the Unix time base
int ByteOffset = 0
DateTime val = UNIX_EPOCH.AddTicks(BitConverter.ToInt64(value, ByteOffset) / 100);
TIME and TIME_OF_DAY types
Convert to TimeSpan in the same way as the DATE type
private static DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, 0);
// Read a structure containing a DATE_AND_TIME on the PLC into a byte array with Compolet (example: Compolet)
byte[] value = compolet1.ReadValiable("struct1");
// Convert the TIME bytes in the byte array to an INT64 and convert 1 ns units to 100 ns units
// Set it in Val as the elapsed time from the Unix time base
int ByteOffset = 8
TimeSpan val = new TimeSpan(BitConverter.ToInt64(value, ByteOffset) / 100);
