Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Last active March 18, 2025 18:50
Show Gist options
  • Save karenpayneoregon/a5d786f3c86b803474443edca6d8783f to your computer and use it in GitHub Desktop.
Save karenpayneoregon/a5d786f3c86b803474443edca6d8783f to your computer and use it in GitHub Desktop.
NodaTime difference between two dates raw

Other than Conventional.cs all code is NodaTime.

public static string CalculateTimeDifference(DateTime futureDate)
{
if (futureDate <= DateTime.Now)
{
return "The provided date must be in the future.";
}
DateTime now = DateTime.Now;
// Calculate total months difference
int months = ((futureDate.Year - now.Year) * 12) + futureDate.Month - now.Month;
if (futureDate.Day < now.Day)
{
months--; // Adjust if the future day is earlier than the current day
}
// Calculate remaining days, hours, and minutes
TimeSpan timeSpan = futureDate - now.AddMonths(months);
int days = timeSpan.Days;
int hours = timeSpan.Hours;
int minutes = timeSpan.Minutes;
// Build the result dynamically
return $"{(months > 0 ? $"{months} months, " : "")}{days} days, {hours} hours, {minutes} minutes.";
}
Console.WriteLine(NodaHelpers.GetTimeDifference(new DateTime(2025, 4, 23, 23, 59, 59)));
using NodaTime;
using static NodaTime.PeriodUnits;
using static NodaTime.SystemClock;
namespace your_namespace;
public class NodaHelpers
{
/// <summary>
/// Calculates the time difference between the current time in a specified time zone
/// and a given future date and time.
/// </summary>
/// <param name="futureDateTime">The future date and time to compare against the current time.</param>
/// <param name="timeZoneId">The identifier of the time zone to use for the calculation.</param>
/// <returns>
/// A string representation of the current time, the future time, and the difference
/// between them in years, months, days, hours, minutes, and seconds.
/// </returns>
public static string GetTimeDifference(DateTime futureDateTime, string timeZoneId = "America/Los_Angeles")
{
DateTimeZone timeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(timeZoneId);
if (timeZone == null)
{
return $"Error: The time zone '{timeZoneId}' is invalid.";
}
ZonedDateTime now = Instance.GetCurrentInstant().InZone(timeZone);
LocalDateTime futureLocal = LocalDateTime.FromDateTime(futureDateTime);
ZonedDateTime future = futureLocal.InZoneLeniently(timeZone);
Period difference = Period.Between(now.LocalDateTime, futureLocal,
Days | Hours | Minutes | Seconds);
return $"Current Time: {now.ToString("MM/dd/yyyy hh:mm:ss", null)}" +
$"\nFuture Time: {future.ToString("MM/dd/yyyy hh:mm:ss", null)}\n" +
$"Difference: {difference.Years} years, {difference.Months} months, " +
$"{difference.Days} days, {difference.Hours} hours, {difference.Minutes} minutes, " +
$"{difference.Seconds} seconds.";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment