Comments (6)
See #687 (comment). For the same reasoning, I think it is best to not provide this natively.
from time.
I understand. I've published time-local
with this functionality.
use time_local::OffsetDateTimeExt;
fn main() {
time_local::init();
let date = std::thread::spawn(|| {
// `time::OffsetDateTime::now_local()` will fail because it queries `time::UtcOffset::current_local_time`, instead we can use:
time::OffsetDateTime::now_utc()
.to_local()
.expect("conversion to local offset with cached value should succeed")
})
.join()
.expect("thread should not panic");
println!("{date:?}")
}
from time.
@mickvangelderen Your solution doesn't actually work, because the offset changes over time, so you can't just have 1 offset, you need to look it up for the particular date you want to convert, which brings you back to the env issue.
from time.
@mickvangelderen Your solution doesn't actually work, because the offset changes over time, so you can't just have 1 offset, you need to look it up for the particular date you want to convert, which brings you back to the env issue.
Yes, that may be an issue for long running applications. In my case, I have a CLI application that just wants to print a bunch of dates using a reasonable local offset. Using the offset at application startup time is fine. I agree it would be good to document this in the crate.
You could argue that the to_local
function should not use a cached value because the name sort of suggests that it will use the local offset for the current machine of the provided date. It should either be named to_local_using_cached_value
or just not exist and use to_offset(cached_local_offset()?)
instead.
@CryZe what would you do for a short-lived application?
from time.
@CryZe I think that indeed I should remove to_local()
as it would be better to explicitly pass the offset.
from time.
I have rewritten the README and changed the API. to_local()
now just returns `self.to_offset(time::UtcOffset::local_offset_at(self)?).
The README reads:
In order to obtain the local time offset, time calls out to libc
s localtime_r
function.
Implementations of localtime_r
, like glibc
and musl
, call getenv("TZ")
to obtain the current value for the TZ
environment variable.
Unfortunately, values returned by getenv()
can be invalidated by calls that modify the environment, like setenv()
, unsetenv()
, or putenv()
.
For example, the following single-threaded application has a potential use after free bug:
char * value = getenv("KEY"); // obtain pointer
setenv("KEY", "new value"); // potential free
printf("KEY = %s", value); // potential use after free
The functions in Rust's std::env
module synchronize access to the environment through a lock.
However, any foreign code (including libc
implementations) is free to modify the environment without acquiring that lock.
This has led to discussion about whether Rust's std::env::set_var
should be marked unsafe.
Under the assumption that accessing the environment is implemented correctly everywhere for single-threaded programs, there can only be issues in multi-threaded programs.
This is why the time crate lets you obtain the UTC offset while the number of threads is 1.
This crate provides a solution for applications that can accept using a cached value of the UTC offset by doing exactly that: caching the UTC offset at the time of invocation.
Here is an example:
use time_local::{OffsetDateTimeExt, UtcOffsetExt};
fn main() {
time_local::init().expect("initialization should succeed before spawning threads");
let date = std::thread::spawn(|| {
// We can not convert a date time to it's local representation.
assert!(time::OffsetDateTime::now_utc()
.to_local()
.is_err(), "to_local should fail");
// We can use the cached UTC offset computed at application startup. Note that this is computing something
// different entirely, but it may be good enough for your application.
time::OffsetDateTime::now_utc().to_offset(time::UtcOffset::cached_local_offset())
})
.join()
.expect("thread should not panic");
println!("{date:?}")
}
Note that a UTC offset depends on both the timezone and a particular date and time.
The cached UTC offset is computed from the current machine's timezone and time.
Changes to the system's local time and/or the TZ
environment variable will not be reflected by the cached UTC offset, and the cached UTC offset used in .to_local()
does not depend on the OffsetDateTime
.
from time.
Related Issues (20)
- `subsec_{milli,micro,nano}seconds` may have over-inclusive documented ranges HOT 1
- Default `impl Deserialize`/`impl Serialize for time::OffsetDateTime` is a footgun HOT 1
- Mark the date_time function from OffsetDateTime as public HOT 1
- Bug with leap second parsing ISO 8601 HOT 6
- Renaming of `FormatItem` is a breaking change HOT 5
- How to use `serde::format_description` with `format_description::well_known` ? HOT 5
- Confusing deprecation message for `time::Instant` HOT 3
- Formatting bug on ISO8601 HOT 6
- Make `format` methods localizable HOT 6
- Error with rust-nightly: type annotations needed for `Box<_>` HOT 7
- Solve "large-dates" ambiguity HOT 1
- parsing: option to [end] to terminate parsing even if there is further input HOT 1
- compile error: time-0.3.29/src/format_description/parse/mod.rs:83:9 "type must be known at this point" HOT 2
- Document status of local-offset support HOT 2
- Ferrocene compiler needs more information about the type of Box<_> at compile time. HOT 1
- Serialization data corruption with Duration and `serde_human_readable` for negative subsecond durations HOT 1
- error[E0282]: type annotations needed for `Box<_>` HOT 4
- Build failure under 1.80.0 HOT 1
- Add what features should be enabled in docs HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from time.