Add {Utc,Local}::now() constructor versions for the `wasm32` arch

While likely providing only incomplete support for WebAssembly, this
commit opens up chrono for use on the wasm32 architecture.
This commit is contained in:
Joey Ezechiels 2018-11-04 23:31:17 +01:00 committed by eV
parent 7412469623
commit 8bfaca9f9b
4 changed files with 32 additions and 3 deletions

View File

@ -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" }

View File

@ -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");

View File

@ -87,9 +87,18 @@ impl Local {
}
/// Returns a `DateTime` which corresponds to the current date.
#[cfg(not(target_arch = "wasm32"))]
pub fn now() -> DateTime<Local> {
tm_to_datetime(oldtime::now())
}
/// Returns a `DateTime` which corresponds to the current date.
#[cfg(target_arch = "wasm32")]
pub fn now() -> DateTime<Local> {
use super::Utc;
let now: DateTime<Utc> = super::Utc::now();
now.with_timezone(&Local)
}
}
impl TimeZone for Local {
@ -179,4 +188,3 @@ mod tests {
"unexpected timestr {:?}", timestr);
}
}

View File

@ -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> { Utc::now().date() }
/// Returns a `DateTime` which corresponds to the current date.
#[cfg(not(target_arch = "wasm32"))]
pub fn now() -> DateTime<Utc> {
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<Utc> {
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") }
}