Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,27 @@ namespace HackerNews.BestStories.Api;

internal sealed class UtcIso8601DateTimeOffsetConverter : JsonConverter<DateTimeOffset>
{
private static readonly string[] Iso8601Formats =
[
"yyyy-MM-dd'T'HH:mm:ssK",
"yyyy-MM-dd'T'HH:mm:ss.FFFFFFFK"
];
Comment thread
Copilot marked this conversation as resolved.

public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
=> DateTimeOffset.Parse(reader.GetString()!);
{
var value = reader.GetString()!;
if (!DateTimeOffset.TryParseExact(
value,
Iso8601Formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out var result))
{
throw new FormatException($"The value '{value}' is not a valid ISO-8601 date/time offset.");
}

return result;
}

public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToUniversalTime()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
@page "/"
@rendermode InteractiveServer
@using System.Globalization
@inject BestStoriesClient Api

<PageTitle>Hacker News Best Stories</PageTitle>
Expand Down Expand Up @@ -143,5 +144,5 @@
private void LastPage() => page = PageCount;

private static string FormatTime(DateTimeOffset value)
=> value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss+00:00");
=> value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss+00:00", CultureInfo.InvariantCulture);
}
4 changes: 2 additions & 2 deletions src/HackerNews.BestStories.React/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<!-- Do not inherit TargetFramework / TreatWarningsAsErrors from the repo root. -->
<!-- Repo-level Directory.Build.props sets <TargetFramework>net10.0</TargetFramework> for every project. That is wrong for an .esproj -->
<!-- MSBuild automatically loads only the nearest Directory.Build.props. -->
<!-- This file does not import the repo root props, keeping their TargetFramework and warning settings out of the .esproj. -->
<PropertyGroup Condition="'$(MSBuildProjectExtension)' == '.esproj'">
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,60 @@ public void Read_ParsesIso8601ValueWithExplicitOffset()
Assert.Equal(new DateTimeOffset(2025, 1, 2, 3, 4, 5, TimeSpan.FromHours(2)), result);
}

[Fact]
public void Read_ThrowsFormatException_ForMalformedValue()
[Theory]
[InlineData("en-US")]
[InlineData("ar-SA")]
[InlineData("th-TH")]
public void Read_ParsesInvariantValues_PreservingInstantAndOffset(string culture)
{
var previous = System.Globalization.CultureInfo.CurrentCulture;
try
{
System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo(culture);
(string Text, int OffsetMinutes, long FractionTicks)[] cases =
[
("2025-01-02T03:04:05Z", 0, 0),
("2025-01-02T03:04:05+02:00", 120, 0),
("2025-01-02T03:04:05.1234567Z", 0, 1234567),
("2025-01-02T03:04:05.1234567+02:00", 120, 1234567),
("2025-01-02T03:04:05.123-05:30", -330, 1230000)
];
Comment thread
Copilot marked this conversation as resolved.

foreach (var (text, offsetMinutes, fractionTicks) in cases)
{
var expected = new DateTimeOffset(2025, 1, 2, 3, 4, 5, TimeSpan.FromMinutes(offsetMinutes))
.AddTicks(fractionTicks);
var result = DeserializeDateTimeOffset(JsonSerializer.Serialize(text));

Assert.Equal(expected, result);
Assert.Equal(expected.Offset, result.Offset);
}
}
finally
{
System.Globalization.CultureInfo.CurrentCulture = previous;
}
}

[Theory]
[InlineData("en-US")]
[InlineData("ar-SA")]
[InlineData("th-TH")]
public void Read_ThrowsFormatException_ForMalformedValue(string culture)
{
Assert.Throws<FormatException>(() => DeserializeDateTimeOffset("\"not-a-date\""));
var previous = System.Globalization.CultureInfo.CurrentCulture;
try
{
System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo(culture);
Assert.Throws<FormatException>(() =>
{
DeserializeDateTimeOffset("\"not-a-date\"");
});
}
finally
{
System.Globalization.CultureInfo.CurrentCulture = previous;
}
}

private DateTimeOffset DeserializeDateTimeOffset(string json)
Expand Down
57 changes: 37 additions & 20 deletions tests/HackerNews.BestStories.Blazor.Tests/Components/HomeTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Globalization;
using System.Net;
using System.Text;
using AwesomeAssertions;
Expand Down Expand Up @@ -70,27 +71,43 @@ public void Renders_error_state_when_service_throws()
cut.Markup.Should().Contain("No stories to display.");
}

[Fact]
public void Renders_story_time_in_utc_format()
[Theory]
[InlineData("en-US")]
[InlineData("ar-SA")]
[InlineData("th-TH")]
public void Renders_story_time_in_utc_format(string cultureName)
{
const string json = """
[{
"title":"Story",
"uri":"https://example.com/1",
"postedBy":"author",
"time":"2024-01-02T03:04:05+02:00",
"score":10,
"commentCount":2
}]
""";
var handler = new StaticHandler(HttpStatusCode.OK, json);
Services.AddSingleton(new BestStoriesClient(
new HttpClient(handler) { BaseAddress = new Uri("http://api/") },
_ => TimeSpan.Zero));

var cut = Render<Home>();

cut.Markup.Should().Contain("2024-01-02T01:04:05+00:00");
var originalCulture = CultureInfo.CurrentCulture;
var originalUiCulture = CultureInfo.CurrentUICulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(cultureName);
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo(cultureName);

const string json = """
[{
"title":"Story",
"uri":"https://example.com/1",
"postedBy":"author",
"time":"2024-01-02T03:04:05+02:00",
"score":10,
"commentCount":2
}]
""";
var handler = new StaticHandler(HttpStatusCode.OK, json);
Services.AddSingleton(new BestStoriesClient(
new HttpClient(handler) { BaseAddress = new Uri("http://api/") },
_ => TimeSpan.Zero));

var cut = Render<Home>();

cut.Find("tbody td.mono").TextContent.Should().Be("2024-01-02T01:04:05+00:00");
}
finally
{
CultureInfo.CurrentCulture = originalCulture;
CultureInfo.CurrentUICulture = originalUiCulture;
}
}

[Fact]
Expand Down
Loading