Skip to content

Commit eca936d

Browse files
committed
Corrected $date parsing of Long values
1 parent 731840a commit eca936d

File tree

2 files changed

+45
-6
lines changed

2 files changed

+45
-6
lines changed

src/main/com/mongodb/util/JSONCallback.java

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import java.text.ParsePosition;
2222
import java.text.SimpleDateFormat;
23+
import java.util.Date;
2324
import java.util.GregorianCalendar;
2425
import java.util.SimpleTimeZone;
2526
import java.util.UUID;
@@ -76,13 +77,21 @@ public Object objectDone(){
7677
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
7778
GregorianCalendar calendar = new GregorianCalendar(new SimpleTimeZone(0, "GMT"));
7879
format.setCalendar(calendar);
79-
String txtdate = (String) b.get("$date");
80-
o = format.parse(txtdate, new ParsePosition(0));
81-
if (o == null) {
82-
// try older format with no ms
83-
format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
84-
format.setCalendar(calendar);
80+
81+
String txtdate = b.get("$date").toString();
82+
83+
try {
84+
// Convert from seconds to ms to match consistency
85+
// with strict JSON serialization
86+
o = new Date( Long.parseLong(txtdate) * 1000l);
87+
} catch (NumberFormatException e) {
8588
o = format.parse(txtdate, new ParsePosition(0));
89+
if (o == null) {
90+
// try older format with no ms
91+
format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
92+
format.setCalendar(calendar);
93+
o = format.parse(txtdate, new ParsePosition(0));
94+
}
8695
}
8796
if (!isStackEmpty()) {
8897
cur().put( name, o );
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.mongodb.util;
2+
3+
import java.text.SimpleDateFormat;
4+
import java.util.Date;
5+
import java.util.GregorianCalendar;
6+
import java.util.SimpleTimeZone;
7+
8+
public class JSONCallbackTest extends com.mongodb.util.TestCase {
9+
10+
@org.testng.annotations.Test(groups = {"basic"})
11+
public void dateParsing(){
12+
long currentTime = System.currentTimeMillis();
13+
Date rightNow = new Date();
14+
rightNow.setTime(currentTime);
15+
16+
SimpleDateFormat format =
17+
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
18+
format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
19+
20+
Date parsedDate = (Date)JSON.parse("{ \"$date\" : "+rightNow.getTime()/1000l+"}");
21+
assertEquals(format.format(rightNow), format.format(parsedDate));
22+
23+
parsedDate = (Date)JSON.parse("{ \"$date\" : \""+rightNow.getTime()/1000l+"\"}");
24+
assertEquals(format.format(rightNow), format.format(parsedDate));
25+
26+
parsedDate = (Date)JSON.parse("{ \"$date\" : \""+format.format(rightNow)+"\"}");
27+
assertEquals(format.format(rightNow), format.format(parsedDate));
28+
}
29+
30+
}

0 commit comments

Comments
 (0)