Skip to content

Commit 72bd6f9

Browse files
committed
We should be setting the dateFormat to what it originally is in PyishDate.
This PR adds a new method which we can use when reconstructing to put the date format back to what it originally was
1 parent 91a3f0e commit 72bd6f9

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

src/main/java/com/hubspot/jinjava/objects/date/PyishDate.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,11 @@ public void setDateFormat(String dateFormat) {
112112
this.dateFormat = dateFormat;
113113
}
114114

115+
public PyishDate withDateFormat(String dateFormat) {
116+
setDateFormat(dateFormat);
117+
return this;
118+
}
119+
115120
public Date toDate() {
116121
return Date.from(date.toInstant());
117122
}
@@ -163,10 +168,12 @@ public boolean equals(Object obj) {
163168
public <T extends Appendable & CharSequence> T appendPyishString(T appendable)
164169
throws IOException {
165170
return (T) appendable
166-
.append('\'')
171+
.append("('")
167172
.append(strftime(FULL_DATE_FORMAT))
168173
.append("'|strtotime(")
169174
.append(PyishObjectMapper.getAsPyishStringOrThrow(FULL_DATE_FORMAT))
175+
.append(")).withDateFormat(")
176+
.append(PyishObjectMapper.getAsPyishStringOrThrow(dateFormat))
170177
.append(')');
171178
}
172179
}

src/test/java/com/hubspot/jinjava/objects/date/PyishDateTest.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,26 @@ public void itPyishSerializes() {
6767
assertThat(d1).isEqualTo(interpreter.getContext().get("foo"));
6868
}
6969

70+
@Test
71+
public void itPyishSerializesWithCustomDateFormat() {
72+
PyishDate d1 = new PyishDate(ZonedDateTime.parse("2013-11-12T14:15:16.170+02:00"));
73+
d1.setDateFormat("yyyy-MM-dd");
74+
JinjavaInterpreter interpreter = new Jinjava().newInterpreter();
75+
interpreter.render("{% set foo = " + PyishObjectMapper.getAsPyishString(d1) + "%}");
76+
PyishDate reconstructed = (PyishDate) interpreter.getContext().get("foo");
77+
assertThat(reconstructed.toString()).isEqualTo("2013-11-12");
78+
}
79+
80+
@Test
81+
public void itDoesntLoseSecondsOnReconstruction() {
82+
PyishDate d1 = new PyishDate(ZonedDateTime.parse("2013-11-12T14:15:16.170+02:00"));
83+
d1.setDateFormat("yyyy-MM-dd");
84+
JinjavaInterpreter interpreter = new Jinjava().newInterpreter();
85+
interpreter.render("{% set foo = " + PyishObjectMapper.getAsPyishString(d1) + "%}");
86+
PyishDate reconstructed = (PyishDate) interpreter.getContext().get("foo");
87+
assertThat(reconstructed.getSecond()).isEqualTo(16);
88+
}
89+
7090
@Test
7191
public void testPyishDateToStringWithCustomDateFormatter() {
7292
PyishDate d1 = new PyishDate(ZonedDateTime.parse("2013-11-12T14:15:16.170+02:00"));

0 commit comments

Comments
 (0)