Skip to content

Serialize DateMath with minimum 3 decimal places #3802

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 7, 2019
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
20 changes: 19 additions & 1 deletion src/Nest/CommonOptions/DateMath/DateMath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public override string ToString()

var sb = new StringBuilder();
var anchor = Self.Anchor.Match(
d => d.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFF") + separator,
d => ToMinThreeDecimalPlaces(d) + separator,
s => s == "now" || s.EndsWith("||", StringComparison.Ordinal) ? s : s + separator
);
sb.Append(anchor);
Expand All @@ -107,6 +107,24 @@ public override string ToString()

return sb.ToString();
}

/// <summary>
/// Formats a <see cref="DateTime"/> to have a minimum of 3 decimal places if there
/// are sub second values
/// </summary>
/// Fixes bug in Elasticsearch: https://github.com/elastic/elasticsearch/pull/41871
private static string ToMinThreeDecimalPlaces(DateTime dateTime)
{
var format = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFF");

if (format.Length > 20 && format.Length < 23)
{
var diff = 23 - format.Length;
return $"{format}{new string('0', diff)}";
}

return format;
}
}

internal class DateMathFormatter : IJsonFormatter<DateMath>
Expand Down
30 changes: 30 additions & 0 deletions src/Tests/Tests.Reproduce/GitHubIssue3719.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using Elastic.Xunit.XunitPlumbing;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Tests.Core.Client;

namespace Tests.Reproduce
{
public class GitHubIssue3719
{
[U]
public void SerializeDateMathWithMinimumThreeDecimalPlacesWhenTens()
{
DateMath dateMath = new DateTime(2019, 5, 7, 12, 0, 0, 20);

var json = TestClient.Default.RequestResponseSerializer.SerializeToString(dateMath, RecyclableMemoryStreamFactory.Default);
json.Should().Be("\"2019-05-07T12:00:00.020\"");
}

[U]
public void SerializeDateMathWithMinimumThreeDecimalPlacesWhenHundreds()
{
DateMath dateMath = new DateTime(2019, 5, 7, 12, 0, 0, 200);

var json = TestClient.Default.RequestResponseSerializer.SerializeToString(dateMath, RecyclableMemoryStreamFactory.Default);
json.Should().Be("\"2019-05-07T12:00:00.200\"");
}
}
}