Parcourir la source

Support exporting Date to time.Time

Dmitry Panov il y a 5 ans
Parent
commit
9af81ddcf0
2 fichiers modifiés avec 32 ajouts et 6 suppressions
  1. 14 6
      runtime.go
  2. 18 0
      runtime_test.go

+ 14 - 6
runtime.go

@@ -1707,13 +1707,21 @@ func (r *Runtime) toReflectValue(v Value, dst reflect.Value, ctx *objectExportCt
 			dst.Set(reflect.ValueOf(exportValue(v, ctx)).Convert(typ))
 			return nil
 		}
-		if typ == typeTime && et.Kind() == reflect.String {
-			tme, ok := dateParse(v.String())
-			if !ok {
-				return fmt.Errorf("could not convert string %v to %v", v, typ)
+		if typ == typeTime {
+			if obj, ok := v.(*Object); ok {
+				if d, ok := obj.self.(*dateObject); ok {
+					dst.Set(reflect.ValueOf(d.time()))
+					return nil
+				}
+			}
+			if et.Kind() == reflect.String {
+				tme, ok := dateParse(v.String())
+				if !ok {
+					return fmt.Errorf("could not convert string %v to %v", v, typ)
+				}
+				dst.Set(reflect.ValueOf(tme))
+				return nil
 			}
-			dst.Set(reflect.ValueOf(tme))
-			return nil
 		}
 	}
 

+ 18 - 0
runtime_test.go

@@ -685,6 +685,24 @@ func TestRuntime_ExportToTime(t *testing.T) {
 	if str != "2018-08-13T15:02:13+02:00" {
 		t.Fatalf("Unexpected value: '%s'", str)
 	}
+
+	d, err := vm.RunString(`new Date(1000)`)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	ti = time.Time{}
+	err = vm.ExportTo(d, &ti)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if ti.UnixNano() != 1000*1e6 {
+		t.Fatal(ti)
+	}
+	if ti.Location() != time.Local {
+		t.Fatalf("Wrong location: %v", ti)
+	}
 }
 
 func ExampleRuntime_ExportTo_func() {