Skip to content

Commit f7668ff

Browse files
authored
Serialize DateMath with minimum 3 decimal places (#3802)
* Serialize DateMath with minimum 3 decimal places This commit ensures that DateMath containing DateTime are always serialized with a minimum of 3 decimal places. elastic/elasticsearch#41871 introduced a bug in Elasticsearch 7.x < 7.1.0 whereby date strings with less than 3 decimal places throw a parser exception. Fixes #3719
1 parent 56a3ac0 commit f7668ff

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/Nest/CommonOptions/DateMath/DateMath.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public override string ToString()
9292

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

108108
return sb.ToString();
109109
}
110+
111+
/// <summary>
112+
/// Formats a <see cref="DateTime"/> to have a minimum of 3 decimal places if there
113+
/// are sub second values
114+
/// </summary>
115+
/// Fixes bug in Elasticsearch: https://github.com/elastic/elasticsearch/pull/41871
116+
private static string ToMinThreeDecimalPlaces(DateTime dateTime)
117+
{
118+
var format = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFF");
119+
120+
if (format.Length > 20 && format.Length < 23)
121+
{
122+
var diff = 23 - format.Length;
123+
return $"{format}{new string('0', diff)}";
124+
}
125+
126+
return format;
127+
}
110128
}
111129

112130
internal class DateMathFormatter : IJsonFormatter<DateMath>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using System;
2+
using Elastic.Xunit.XunitPlumbing;
3+
using Elasticsearch.Net;
4+
using FluentAssertions;
5+
using Nest;
6+
using Tests.Core.Client;
7+
8+
namespace Tests.Reproduce
9+
{
10+
public class GitHubIssue3719
11+
{
12+
[U]
13+
public void SerializeDateMathWithMinimumThreeDecimalPlacesWhenTens()
14+
{
15+
DateMath dateMath = new DateTime(2019, 5, 7, 12, 0, 0, 20);
16+
17+
var json = TestClient.Default.RequestResponseSerializer.SerializeToString(dateMath, RecyclableMemoryStreamFactory.Default);
18+
json.Should().Be("\"2019-05-07T12:00:00.020\"");
19+
}
20+
21+
[U]
22+
public void SerializeDateMathWithMinimumThreeDecimalPlacesWhenHundreds()
23+
{
24+
DateMath dateMath = new DateTime(2019, 5, 7, 12, 0, 0, 200);
25+
26+
var json = TestClient.Default.RequestResponseSerializer.SerializeToString(dateMath, RecyclableMemoryStreamFactory.Default);
27+
json.Should().Be("\"2019-05-07T12:00:00.200\"");
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)