将C# DateTime的8字节Ticks转换为JavaScript DateTime的实现方案
Got it, let's tackle this problem head-on—you need to parse the 8-byte C# DateTime Ticks from your existing packets in JavaScript, no changes to the server-side data required. Here's the breakdown and working code:
Key Background
First, let's align on the time bases:
- C# Ticks: Represents 100-nanosecond intervals since
0001-01-01 00:00:00 UTC(this is the .NET epoch). - JavaScript Date: Uses milliseconds since
1970-01-01 00:00:00 UTC(Unix epoch).
The fixed tick difference between these two epochs is 621355968000000000—this is how many ticks pass from the .NET epoch to the Unix epoch.
Step-by-Step Conversion
1. Parse the 8-byte Ticks from the Packet
C# stores long (64-bit signed integer) values in little-endian byte order by default (when using BitConverter.GetBytes()). We'll use JavaScript's DataView to correctly read this 64-bit value without precision loss (critical, since 64-bit integers exceed JavaScript Number's 53-bit precision limit—so we use BigInt).
2. Convert Ticks to JavaScript Date
Subtract the epoch tick difference, convert from 100-nanosecond ticks to milliseconds, then create a Date object.
Working Code Example
function convertCSharpTicksToJsDate(ticksBuffer) { // Fixed tick count from .NET epoch (0001-01-01) to Unix epoch (1970-01-01) const ticksToUnixEpoch = 621355968000000000n; // Read 64-bit signed integer in little-endian (matches C#'s BitConverter default) const dataView = new DataView(ticksBuffer); const csharpTicks = dataView.getBigInt64(0, true); // Calculate milliseconds since Unix epoch: // (C# Ticks - epoch difference) / 10000 (since 1ms = 10000 ticks) const msSinceUnixEpoch = (csharpTicks - ticksToUnixEpoch) / 10000n; // Convert BigInt to Number (safe here since msSinceUnixEpoch fits in 53 bits) return new Date(Number(msSinceUnixEpoch)); }
Usage Notes
- Byte Order Check: If your server uses big-endian (network byte order) to send the ticks, change the second parameter in
getBigInt64tofalse:dataView.getBigInt64(0, false). - Time Zone Handling: Ensure your server sends UTC ticks (use
DateTime.UtcNow.Ticksin C# instead of local time). The JavaScriptDateobject will automatically handle client-side time zone conversion when displaying the date. - Validation Test: To verify, generate a tick value in C#:
Then test in JS by creating a buffer with those ticks and passing it to the function—the resulting date should match the C#DateTime utcNow = DateTime.UtcNow; long ticks = utcNow.Ticks; Console.WriteLine(ticks); // Copy this valueutcNowvalue.
内容的提问来源于stack exchange,提问作者Gauthier

