diff --git a/src/KubernetesClient/KubernetesJson.cs b/src/KubernetesClient/KubernetesJson.cs index 69ecdf43e..35cfe3acb 100644 --- a/src/KubernetesClient/KubernetesJson.cs +++ b/src/KubernetesClient/KubernetesJson.cs @@ -60,12 +60,20 @@ public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSeri // Output as RFC3339Micro var date = value.ToUniversalTime(); - var basePart = date.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture); - var frac = date.ToString(".ffffff", CultureInfo.InvariantCulture) - .TrimEnd('0') - .TrimEnd('.'); - - writer.WriteStringValue(basePart + frac + "Z"); + // Check if there are any fractional seconds + var ticks = date.Ticks % TimeSpan.TicksPerSecond; + if (ticks == 0) + { + // No fractional seconds - use format without fractional part + var basePart = date.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture); + writer.WriteStringValue(basePart + "Z"); + } + else + { + // Has fractional seconds - always use exactly 6 decimal places + var formatted = date.ToString(RFC3339MicroFormat, CultureInfo.InvariantCulture); + writer.WriteStringValue(formatted); + } } } diff --git a/tests/KubernetesClient.Tests/KubernetesJsonTests.cs b/tests/KubernetesClient.Tests/KubernetesJsonTests.cs index 785e38fea..e8f199456 100644 --- a/tests/KubernetesClient.Tests/KubernetesJsonTests.cs +++ b/tests/KubernetesClient.Tests/KubernetesJsonTests.cs @@ -142,4 +142,31 @@ public void ReadWriteDatesJson() Assert.Equal(kManifest, jsonFromObj2); } + + [Fact] + public void DateTimeWithFractionalSecondsAlwaysHasSixDigits() + { + // Test that datetime fields with fractional seconds always output exactly 6 decimal places + // This is required by Kubernetes API which expects RFC3339Micro format + + // Create a datetime with 5 digits of precision (962170 microseconds = .96217 seconds) + var dt = new DateTime(2025, 11, 17, 22, 52, 34, 962, DateTimeKind.Utc).AddTicks(1700); + + var secret = new V1Secret + { + Metadata = new V1ObjectMeta + { + Name = "test-secret", + CreationTimestamp = dt, + }, + }; + + var json = KubernetesJson.Serialize(secret); + + // Verify the datetime is serialized with exactly 6 decimal places + Assert.Contains("2025-11-17T22:52:34.962170Z", json); + + // Also verify it doesn't have 5 digits (which would fail in Kubernetes) + Assert.DoesNotContain("2025-11-17T22:52:34.96217Z", json); + } }