Added extension for ISO 8601 date-time format

This commit is contained in:
2025-10-10 12:32:25 +02:00
parent 932b8697ae
commit 4eb0dcb028
3 changed files with 85 additions and 1 deletions

View File

@@ -0,0 +1,34 @@
namespace AMWD.Net.Api.Cloudflare
{
/// <summary>
/// Extension methods for <see cref="DateTime"/>s.
/// </summary>
public static class DateTimeExtensions
{
private const string Iso8601Format = "yyyy-MM-dd'T'HH:mm:ss'Z'";
/// <summary>
/// Converts the specified <see cref="DateTime"/> to its ISO 8601 string representation.
/// </summary>
/// <remarks>
/// This method ensures that the resulting string conforms to the ISO 8601 standard, which is
/// commonly used for representing dates and times in a machine-readable format.
/// </remarks>
/// <param name="dateTime"> The <see cref="DateTime"/> instance to convert.</param>
/// <returns>
/// A string representing the <paramref name="dateTime"/> in ISO 8601 format.
/// <br/>
/// If the <see cref="DateTime.Kind"/> property is <see cref="DateTimeKind.Local"/>, the value is first converted to <see cref="DateTimeKind.Utc"/>.
/// <br/>
/// If the <see cref="DateTime.Kind"/> is <see cref="DateTimeKind.Unspecified"/>, it is treated as <see cref="DateTimeKind.Utc"/>.
/// </returns>
public static string ToIso8601Format(this DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Local)
return dateTime.ToUniversalTime().ToString(Iso8601Format);
// DateTimeKind.Unspecified is treated as UTC
return dateTime.ToString(Iso8601Format);
}
}
}

View File

@@ -9,7 +9,7 @@
var dict = new Dictionary<string, string>();
if (HoldAfter.HasValue)
dict.Add("hold_after", HoldAfter.Value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"));
dict.Add("hold_after", HoldAfter.Value.ToIso8601Format());
return dict;
}

View File

@@ -0,0 +1,50 @@
using AMWD.Net.Api.Cloudflare;
namespace Cloudflare.Tests.Extensions
{
[TestClass]
public class DateTimeExtensionsTest
{
private const string Format = "yyyy-MM-dd'T'HH:mm:ss'Z'";
[TestMethod]
public void ShouldReturnIsoStringForUtc()
{
// Arrange
var dateTime = new DateTime(2025, 10, 10, 1, 2, 3, DateTimeKind.Utc);
// Act
string isoString = dateTime.ToIso8601Format();
// Assert
Assert.AreEqual(dateTime.ToString(Format), isoString);
}
[TestMethod]
public void ShouldReturnIsoStringForUnspecified()
{
// Arrange
var dateTime = new DateTime(2025, 10, 10, 1, 2, 3, DateTimeKind.Unspecified);
// Act
string isoString = dateTime.ToIso8601Format();
// Assert
Assert.AreEqual(dateTime.ToString(Format), isoString);
}
[TestMethod]
public void ShouldReturnIsoStringForLocal()
{
// Arrange
var dateTime = new DateTime(2025, 10, 10, 1, 2, 3, DateTimeKind.Local);
var offset = TimeZoneInfo.Local.GetUtcOffset(dateTime);
// Act
string isoString = dateTime.ToIso8601Format();
// Assert
Assert.AreEqual(dateTime.Subtract(offset).ToString(Format), isoString);
}
}
}