You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将C# DateTime的8字节Ticks转换为JavaScript DateTime的实现方案

Convert C# DateTime Ticks (8-byte) to 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 getBigInt64 to false: dataView.getBigInt64(0, false).
  • Time Zone Handling: Ensure your server sends UTC ticks (use DateTime.UtcNow.Ticks in C# instead of local time). The JavaScript Date object will automatically handle client-side time zone conversion when displaying the date.
  • Validation Test: To verify, generate a tick value in C#:
    DateTime utcNow = DateTime.UtcNow;
    long ticks = utcNow.Ticks;
    Console.WriteLine(ticks); // Copy this value
    
    Then test in JS by creating a buffer with those ticks and passing it to the function—the resulting date should match the C# utcNow value.

内容的提问来源于stack exchange,提问作者Gauthier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:43:01