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 @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,29 @@ public static bool IsDateInSameTimeZone()
var secondDate = new DateTime(2021, 05, 06, 12, 0, 0, DateTimeKind.Utc);
var firstDateAsUtc = firstDate.ToUniversalTime();

if (firstDateAsUtc.Equals(secondDate))
{
return true;
}

return false;
return firstDateAsUtc.Equals(secondDate);
}

public static bool IsDatePrecisionSame()
{
var firstDate = new DateTime(2021, 05, 06, 12, 0, 0);
var secondDate = new DateTime(2021, 05, 06, 12, 0, 0, 500);

if (firstDate == secondDate)
{
return true;
}
return firstDate == secondDate;
}

public static (bool AreClose, bool SameDay, bool SameDayViaDateOnly) CompareWithTolerance()
{
var firstDate = new DateTime(2021, 05, 06, 12, 0, 0);
var secondDate = new DateTime(2021, 05, 06, 12, 0, 0, 500);

var tolerance = TimeSpan.FromMilliseconds(1);
var areClose = (firstDate - secondDate).Duration() <= tolerance;

var sameDay = firstDate.Date == secondDate.Date;
var sameDayViaDateOnly = DateOnly.FromDateTime(firstDate) == DateOnly.FromDateTime(secondDate);

return false;
return (areClose, sameDay, sameDayViaDateOnly);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ static void Main(string[] args)
{
Console.WriteLine("Date precisions are different.");
}

// Comparing DateTime values with a tolerance, and comparing by date only
var (areClose, sameDay, sameDayViaDateOnly) = Examples.CompareWithTolerance();
Console.WriteLine($"Within 1ms tolerance: {areClose}");
Console.WriteLine($"Same day (Date property): {sameDay}");
Console.WriteLine($"Same day (DateOnly): {sameDayViaDateOnly}");
}

private static void ShowResult(DateTime firstDate, DateTime secondDate, int result)
Expand Down
2 changes: 1 addition & 1 deletion dotnet-datetime/CompareDateTimeInCSharp/Tests/Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

Expand Down
Loading