diff --git a/Cargo.toml b/Cargo.toml index cf2da02..82b8351 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,12 @@ num-traits = { version = "0.2", default-features = false } rustc-serialize = { version = "0.3.20", optional = true } serde = { version = "1", optional = true } +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen = { version = "0.2" } +js-sys = "0.3" # contains FFI bindings for the JS Date API + + + [dev-dependencies] serde_json = { version = "1" } serde_derive = { version = "1" } diff --git a/src/lib.rs b/src/lib.rs index 0df5cdd..5a11eb5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -414,6 +414,10 @@ extern crate serde as serdelib; #[cfg(test)] #[macro_use] extern crate doc_comment; +#[cfg(target_arch = "wasm32")] +extern crate wasm_bindgen; +#[cfg(target_arch = "wasm32")] +extern crate js_sys; #[cfg(test)] doctest!("../README.md"); diff --git a/src/offset/local.rs b/src/offset/local.rs index 6aa4ab7..cce193b 100644 --- a/src/offset/local.rs +++ b/src/offset/local.rs @@ -87,9 +87,18 @@ impl Local { } /// Returns a `DateTime` which corresponds to the current date. + #[cfg(not(target_arch = "wasm32"))] pub fn now() -> DateTime { tm_to_datetime(oldtime::now()) } + + /// Returns a `DateTime` which corresponds to the current date. + #[cfg(target_arch = "wasm32")] + pub fn now() -> DateTime { + use super::Utc; + let now: DateTime = super::Utc::now(); + now.with_timezone(&Local) + } } impl TimeZone for Local { @@ -179,4 +188,3 @@ mod tests { "unexpected timestr {:?}", timestr); } } - diff --git a/src/offset/utc.rs b/src/offset/utc.rs index d4e8d10..83b92ac 100644 --- a/src/offset/utc.rs +++ b/src/offset/utc.rs @@ -4,7 +4,7 @@ //! The UTC (Coordinated Universal Time) time zone. use std::fmt; -#[cfg(feature="clock")] +#[cfg(all(feature="clock", not(target_arch = "wasm32")))] use oldtime; use naive::{NaiveDate, NaiveDateTime}; @@ -38,11 +38,23 @@ impl Utc { pub fn today() -> Date { Utc::now().date() } /// Returns a `DateTime` which corresponds to the current date. + #[cfg(not(target_arch = "wasm32"))] pub fn now() -> DateTime { let spec = oldtime::get_time(); let naive = NaiveDateTime::from_timestamp(spec.sec, spec.nsec as u32); DateTime::from_utc(naive, Utc) } + + /// Returns a `DateTime` which corresponds to the current date. + #[cfg(target_arch = "wasm32")] + pub fn now() -> DateTime { + let now = js_sys::Date::new_0(); + let millisecs_since_unix_epoch: u64 = now.get_time() as u64; + let secs = millisecs_since_unix_epoch / 1000; + let nanos = 1_000_000 * (millisecs_since_unix_epoch - 1000 * secs); + let naive = NaiveDateTime::from_timestamp(secs as i64, nanos as u32); + DateTime::from_utc(naive, Utc) + } } impl TimeZone for Utc { @@ -72,4 +84,3 @@ impl fmt::Debug for Utc { impl fmt::Display for Utc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UTC") } } -