diff --git a/Cargo.toml b/Cargo.toml index e25e427..450805b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,10 @@ categories = ["network-programming", "data-structures", "cryptography"] default = ["alloc"] alloc = [] std = ["alloc"] +wasm-bindgen = ["time/wasm-bindgen"] + +[dependencies] +time = { version = "0.3", optional = true } [package.metadata.docs.rs] all-features = true diff --git a/src/lib.rs b/src/lib.rs index c725880..c1750b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -514,11 +514,20 @@ impl UnixTime { /// The current time, as a `UnixTime` #[cfg(feature = "std")] pub fn now() -> Self { - Self::since_unix_epoch( - SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .unwrap(), // Safe: this code did not exist before 1970. - ) + #[cfg(feature = "wasm-bindgen")] { + Self::since_unix_epoch( + Duration::from_secs(time::OffsetDateTime::now_utc().unix_timestamp() as u64), + ) + } + + #[cfg(not(feature = "wasm-bindgen"))] + { + Self::since_unix_epoch( + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap(), // Safe: this code did not exist before 1970. + ) + } } /// Convert a `Duration` since the start of 1970 to a `UnixTime`