Skip to content

Commit

Permalink
Fix DateTime.Parse with AssumeUniversal style option (#111729)
Browse files Browse the repository at this point in the history
* Fix DateTime.Parse with AssumeUniversal style option

* Apply suggestions from code review

Co-authored-by: Stephen Toub <[email protected]>

---------

Co-authored-by: Stephen Toub <[email protected]>
  • Loading branch information
tarekgh and stephentoub authored Jan 23, 2025
1 parent 7e8f0a5 commit f196875
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3792,22 +3792,13 @@ private static bool CheckNewValue(scoped ref int currentValue, int newValue, cha

private static DateTime GetDateTimeNow(scoped ref DateTimeResult result, scoped ref DateTimeStyles styles)
{
if ((result.flags & ParseFlags.CaptureOffset) != 0)
if ((result.flags & (ParseFlags.CaptureOffset | ParseFlags.TimeZoneUsed)) == (ParseFlags.CaptureOffset | ParseFlags.TimeZoneUsed))
{
if ((result.flags & ParseFlags.TimeZoneUsed) != 0)
{
// use the supplied offset to calculate 'Now'
return new DateTime(DateTime.UtcNow.Ticks + result.timeZoneOffset.Ticks, DateTimeKind.Unspecified);
}
else if ((styles & DateTimeStyles.AssumeUniversal) != 0)
{
// assume the offset is Utc
return DateTime.UtcNow;
}
// use the supplied offset to calculate 'Now'
return new DateTime(DateTime.UtcNow.Ticks + result.timeZoneOffset.Ticks, DateTimeKind.Unspecified);
}

// assume the offset is Local
return DateTime.Now;
return (styles & DateTimeStyles.AssumeUniversal) != 0 ? DateTime.UtcNow : DateTime.Now;
}

private static bool CheckDefaultDateTime(scoped ref DateTimeResult result, scoped ref Calendar cal, DateTimeStyles styles)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2687,6 +2687,17 @@ public void TestRoundTrippingDateTimeAndFileTime()
Assert.Equal(now, roundTrippedDateTime);
}

[Fact]
public void TestParseTimeOnlyStringWithAssumeUtcOption()
{
DateTime utcNow1 = DateTime.UtcNow;
DateTime dt = DateTime.Parse("13:30", null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
DateTime utcNow2 = DateTime.UtcNow;

// Ensure the parsed date part is in UTC.
Assert.InRange(dt.Date, utcNow1.Date, utcNow2.Date);
}

[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void TestTimeSynchronizationWithTheSystem()
Expand Down

0 comments on commit f196875

Please sign in to comment.