Add Javascript time methods to base::Time.


Review URL: https://chromiumcodereview.appspot.com/10536061

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@141317 0039d316-1c4b-4281-b951-d872f2087c98


CrOS-Libchrome-Original-Commit: 42132be3f9f8aadc2de3f8c29ece41e19a4f6281
diff --git a/base/time.cc b/base/time.cc
index 39a8b56..f04ebbc 100644
--- a/base/time.cc
+++ b/base/time.cc
@@ -93,6 +93,23 @@
 }
 
 // static
+Time Time::FromJsTime(double ms_since_epoch) {
+  // The epoch is a valid time, so this constructor doesn't interpret
+  // 0 as the null time.
+  return Time(static_cast<int64>(ms_since_epoch * kMicrosecondsPerMillisecond) +
+              kTimeTToMicrosecondsOffset);
+}
+
+double Time::ToJsTime() const {
+  if (us_ == 0) {
+    // Preserve 0 so the invalid result doesn't depend on the platform.
+    return 0;
+  }
+  return (static_cast<double>(us_ - kTimeTToMicrosecondsOffset) /
+          kMicrosecondsPerMillisecond);
+}
+
+// static
 Time Time::UnixEpoch() {
   Time time;
   time.us_ = kTimeTToMicrosecondsOffset;
diff --git a/base/time.h b/base/time.h
index 5eac215..1487276 100644
--- a/base/time.h
+++ b/base/time.h
@@ -266,6 +266,12 @@
   static Time FromDoubleT(double dt);
   double ToDoubleT() const;
 
+  // Converts to/from the Javascript convention for times, a number of
+  // milliseconds since the epoch:
+  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
+  static Time FromJsTime(double ms_since_epoch);
+  double ToJsTime() const;
+
 #if defined(OS_POSIX)
   struct timeval ToTimeVal() const;
 #endif
diff --git a/base/time_unittest.cc b/base/time_unittest.cc
index cb1f839..f89fc8b 100644
--- a/base/time_unittest.cc
+++ b/base/time_unittest.cc
@@ -88,6 +88,16 @@
   EXPECT_EQ(0, Time::FromTimeT(0).ToInternalValue());
 }
 
+// Test conversions to/from javascript time.
+TEST_F(TimeTest, JsTime) {
+  Time epoch = Time::FromJsTime(0.0);
+  EXPECT_EQ(epoch, Time::UnixEpoch());
+  Time t = Time::FromJsTime(700000.3);
+  EXPECT_EQ(700.0003, t.ToDoubleT());
+  t = Time::FromDoubleT(800.73);
+  EXPECT_EQ(800730.0, t.ToJsTime());
+}
+
 TEST_F(TimeTest, FromExplodedWithMilliseconds) {
   // Some platform implementations of FromExploded are liable to drop
   // milliseconds if we aren't careful.