Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/guides/runtime/timezone.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,18 @@ process.env.TZ = "America/New_York";

new Date().getHours(); // => 21
```

---

`TZ` takes a time zone name, and two other forms that the C library reads.

| Value of `TZ` | Time zone |
| ------------------- | ------------------------------------ |
| `America/New_York` | `America/New_York` |
| `:America/New_York` | `America/New_York` |
| `MSK-3` | `Etc/GMT-3`, three hours east of UTC |
| `GMT+3` | `Etc/GMT+3`, three hours west of UTC |

`MSK-3` and `GMT+3` are POSIX values: a name for the zone, then the hours to add to local time to get UTC. The offset counts west of Greenwich. Bun reads a POSIX value of whole hours from `XYZ-14` (14 hours east of UTC) to `XYZ12` (12 hours west). For an offset with minutes or a zone with daylight saving time, set the time zone name, such as `Asia/Kolkata` or `America/New_York`.

A [standalone executable](/bundler/executables) and a [macro](/bundler/macros) do not read a POSIX value when they start. Set a time zone name for them.
8 changes: 8 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -776,6 +776,14 @@ declare module "bun" {
NODE_ENV?: string;
/**
* Set to change the default timezone at runtime
*
* The value is a time zone name such as `"America/New_York"`, the same
* with a colon before it, or a POSIX value of whole hours such as
* `"MSK-3"` (three hours east of UTC). Bun reads a POSIX value from
* `"XYZ-14"` (14 hours east) to `"XYZ12"` (12 hours west). For an offset
* with minutes or a zone with daylight saving time, use the time zone
* name. A standalone executable and a macro do not read a POSIX value
* when they start.
*/
TZ?: string;
}
Expand Down
5 changes: 3 additions & 2 deletions src/jsc/JSGlobalObject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,8 @@ impl JSGlobalObject {
JSGlobalObject__clearTerminationException(self)
}

pub fn set_time_zone(&self, time_zone: &EncodedSlice) -> bool {
/// Sets the time zone of the process from the `TZ` that it starts with.
pub fn set_time_zone(&self, time_zone: &EncodedSlice) {
JSGlobalObject__setTimeZone(self, time_zone)
}

Expand Down Expand Up @@ -1461,7 +1462,7 @@ unsafe extern "C" {
safe fn JSGlobalObject__clearExceptionExceptTermination(this: &JSGlobalObject) -> bool;
safe fn JSGlobalObject__clearTerminationException(this: &JSGlobalObject);
safe fn JSGlobalObject__hasException(this: &JSGlobalObject) -> bool;
safe fn JSGlobalObject__setTimeZone(this: &JSGlobalObject, time_zone: &EncodedSlice) -> bool;
safe fn JSGlobalObject__setTimeZone(this: &JSGlobalObject, time_zone: &EncodedSlice);
safe fn JSGlobalObject__tryTakeException(this: &JSGlobalObject) -> JSValue;

// safe: `JSGlobalObject` is an opaque `UnsafeCell`-backed ZST handle (`&` is
Expand Down
3 changes: 1 addition & 2 deletions src/jsc/VirtualMachine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6152,8 +6152,7 @@ impl VirtualMachine {
self.default_tls_reject_unauthorized = None;
self.default_verbose_fetch.set(None);
if let Some(tz) = self.test_isolation_state.time_zone.as_deref() {
let _ = self
.global()
self.global()
.set_time_zone(&bun_core::EncodedSlice::from_bytes(tz));
}
if let Some(snapshot) = self.test_isolation_state.proxy_env.as_ref() {
Expand Down
153 changes: 141 additions & 12 deletions src/jsc/bindings/JSEnvironmentVariableMap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
#include "SharedEnvStore.h"
#include "wtf/NeverDestroyed.h"
#include "WebCoreJSBuiltins.h"
#include <wtf/text/MakeString.h>

using namespace JSC;

Expand All @@ -47,6 +48,9 @@ using namespace WebCore;

void invalidateLiveDateInstanceCaches(JSC::VM& vm)
{
// The walk stops every allocator of the heap. No Date has a local time to drop before one has computed it.
if (!vm.dateCache.takeMayHaveCachedLocalGregorianDateTime())
return;
JSC::HeapIterationScope iterationScope(vm.heap);
vm.heap.dateInstanceSpace.forEachLiveCell([](JSC::HeapCell* cell, JSC::HeapCell::Kind) -> IterationStatus {
static_cast<JSC::DateInstance*>(static_cast<JSC::JSCell*>(cell))->invalidateCachedLocalGregorianDateTime();
Expand All @@ -63,6 +67,137 @@ void resetDateCachesAfterTimeZoneChange(JSC::VM& vm)
invalidateLiveDateInstanceCaches(vm);
}

bool setProcessTimeZone(JSC::VM& vm, StringView zoneID)
{
// The longest zone name has 32 characters. ICU makes a copy of a value before it rejects it.
static constexpr unsigned maxZoneIDLength = 128;
if (zoneID.length() > maxZoneIDLength || !WTF::setTimeZoneOverride(zoneID))
return false;
resetDateCachesAfterTimeZoneChange(vm);
return true;
}

void clearProcessTimeZone(JSC::VM& vm)
{
WTF::setTimeZoneOverride(String());
resetDateCachesAfterTimeZoneChange(vm);
}

struct PosixStandardTime {
int32_t secondsWest { 0 };
bool isWholeValue { false };
};

// A POSIX TZ value starts `std offset`: a name, then the [+-]hh[:mm[:ss]] to add to local time to get UTC.
static std::optional<PosixStandardTime> parsePosixStandardTime(StringView text)
{
unsigned position = 0;
auto peek = [&]() -> char16_t { return position < text.length() ? text[position] : 0; };
// The C library reads every digit of a field: "XYZ-003" is three hours, and "GMT+0000" is UTC.
auto consumeNumber = [&](int32_t max) -> std::optional<int32_t> {
unsigned start = position;
int32_t value = 0;
for (; isASCIIDigit(peek()); ++position)
value = std::min(value * 10 + (text[position] - '0'), max + 1);
if (position == start || value > max)
return std::nullopt;
return value;
};

if (peek() == '<') {
unsigned start = ++position;
while (isASCIIAlphanumeric(peek()) || peek() == '+' || peek() == '-')
++position;
if (position - start < 3 || peek() != '>')
return std::nullopt;
++position;
} else {
while (isASCIIAlpha(peek()))
++position;
if (position < 3)
return std::nullopt;
}

bool isEast = peek() == '-';
if (isEast || peek() == '+')
++position;
auto hours = consumeNumber(24);
if (!hours)
return std::nullopt;
int32_t seconds = hours.value() * 3600;
for (int32_t unit : { 60, 1 }) {
if (peek() != ':')
break;
++position;
auto part = consumeNumber(59);
if (!part)
return std::nullopt;
seconds += part.value() * unit;
}
return PosixStandardTime { isEast ? -seconds : seconds, position == text.length() };
}

// "Etc/GMT-14" to "Etc/GMT+12" are the zones a whole number of hours from UTC. Their sign counts west, as in TZ.
static String zoneIDForWholeHoursWest(int32_t secondsWest)
{
int32_t hoursWest = secondsWest / 3600;
if (secondsWest % 3600 || hoursWest < -14 || hoursWest > 12)
return String();
return makeString("Etc/GMT"_s, hoursWest > 0 ? '+' : '-', static_cast<unsigned>(std::abs(hoursWest)));
}

// ICU reads "GMT+3" as three hours east. In TZ it is a POSIX value, three hours west.
static bool isPosixOffsetFromGMT(StringView value)
{
constexpr auto gmt = "gmt"_s;
if (value.length() <= gmt.length() || !startsWithLettersIgnoringASCIICase(value, gmt))
return false;
char16_t next = value[gmt.length()];
return next == '+' || next == '-';
}

static bool hasProcessTimeZone()
{
Vector<char16_t, 32> zoneID;
WTF::getTimeZoneOverride(zoneID);
return !zoneID.isEmpty();
}

void applyTimeZoneFromEnv(JSC::VM& vm, const String& value, TimeZoneWriter writer)
{
StringView name = value;
if (name.startsWith(':'))
name = name.substring(1);
// Only the C library can read the tzfile at a path, and what follows `std offset` in a POSIX value.
bool isForHost = value.isEmpty() || name.startsWith('/');
if (!isForHost) {
// "posix/" and "right/" are directories of tzfiles: a file name follows them, and not a POSIX value.
bool isFileName = false;
for (auto directory : { "posix/"_s, "right/"_s }) {
if (name.startsWith(directory)) {
name = name.substring(directory.length());
isFileName = true;
break;
}
}
if (!name.isEmpty() && !isPosixOffsetFromGMT(name) && setProcessTimeZone(vm, name))
return;
Comment thread
robobun marked this conversation as resolved.
Resolved
if (auto standard = isFileName ? std::nullopt : parsePosixStandardTime(name)) {
String zoneID = standard->isWholeValue ? zoneIDForWholeHoursWest(standard->secondsWest) : String();
if (!zoneID.isNull() && setProcessTimeZone(vm, zoneID))
return;
isForHost = true;
}
}
// Node gives UTC for an assigned name that no zone has: https://github.com/nodejs/node/blob/v26.3.0/src/node_env_var.cc#L78-L105
if (!isForHost && writer == TimeZoneWriter::Assignment && setProcessTimeZone(vm, "UTC"_s))
return;
// A start has no zone to give back, and the restore of `bun test --isolate` has one only when a file set it.
if (writer == TimeZoneWriter::Start && !hasProcessTimeZone())
return;
clearProcessTimeZone(vm);
Comment thread
robobun marked this conversation as resolved.
Resolved
}

const JSC::ClassInfo JSEnvironmentVariableMap::s_info = { "ProcessEnv"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSEnvironmentVariableMap) };

// Node's EnvSetter DEP0104 (https://github.com/nodejs/node/blob/main/src/node_env_var.cc): once per
Expand Down Expand Up @@ -345,10 +480,8 @@ bool JSEnvironmentVariableMap::deleteProperty(JSCell* cell, JSGlobalObject* glob
// the CustomAccessor and existing Dates keep the old offset. put() handles re-set.
auto* uid = propertyName.publicName();
if (uid && WTF::equal(uid, "TZ"_s)) {
if (shouldApplyTZSideEffect(globalObject)) {
WTF::setTimeZoneOverride(String());
resetDateCachesAfterTimeZoneChange(vm);
}
if (shouldApplyTZSideEffect(globalObject))
clearProcessTimeZone(vm);
auto* clientData = WebCore::clientData(vm);
DeletePropertySlot dataSlot;
Base::deleteProperty(cell, globalObject, clientData->builtinNames().dataPrivateName(), dataSlot);
Expand Down Expand Up @@ -520,10 +653,8 @@ JSC_DEFINE_HOST_FUNCTION(jsProcessEnvResetForDelete, (JSGlobalObject * globalObj
auto keyView = asString(key)->view(globalObject);
RETURN_IF_EXCEPTION(scope, {});
if (WTF::equal(keyView, "TZ"_s)) {
if (shouldApplyTZSideEffect(globalObject)) {
WTF::setTimeZoneOverride(String());
resetDateCachesAfterTimeZoneChange(vm);
}
if (shouldApplyTZSideEffect(globalObject))
clearProcessTimeZone(vm);
} else if (WTF::equal(keyView, "NODE_TLS_REJECT_UNAUTHORIZED"_s)) {
applyTLSRejectFromString(globalObject, String());
}
Expand Down Expand Up @@ -702,8 +833,7 @@ static void applyTZFromString(JSGlobalObject* globalObject, const String& value)
{
if (!shouldApplyTZSideEffect(globalObject))
return;
if (value.length() < 32 && WTF::setTimeZoneOverride(value))
resetDateCachesAfterTimeZoneChange(JSC::getVM(globalObject));
applyTimeZoneFromEnv(JSC::getVM(globalObject), value, TimeZoneWriter::Assignment);
}
static void applyTLSRejectFromString(JSGlobalObject*, const String& value)
{
Expand Down Expand Up @@ -806,8 +936,7 @@ bool JSSharedEnvMap::deleteProperty(JSCell* cell, JSGlobalObject* globalObject,
String key(uid);
String normalizedKey = SharedEnvStore::normalizeKey(key);
if (normalizedKey == "TZ"_s && shouldApplyTZSideEffect(globalObject)) {
WTF::setTimeZoneOverride(String());
resetDateCachesAfterTimeZoneChange(JSC::getVM(globalObject));
clearProcessTimeZone(JSC::getVM(globalObject));
} else if (normalizedKey == "NODE_TLS_REJECT_UNAUTHORIZED"_s) {
applyTLSRejectFromString(globalObject, String());
} else if (isProxyEnvVarName(JSC::getVM(globalObject), normalizedKey)) {
Expand Down
16 changes: 16 additions & 0 deletions src/jsc/bindings/JSEnvironmentVariableMap.h
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,22 @@ void invalidateLiveDateInstanceCaches(JSC::VM&);
// together; every caller that changes the time zone override uses this instead.
void resetDateCachesAfterTimeZoneChange(JSC::VM&);

// Sets the time zone of the process to a zone name or a custom ID, as ICU reads them. False, and no change, for another value.
[[nodiscard]] bool setProcessTimeZone(JSC::VM&, WTF::StringView zoneID);

// Gives the time zone of the process back to the host.
void clearProcessTimeZone(JSC::VM&);

enum class TimeZoneWriter : uint8_t {
// The TZ the process starts with, from the environment or a .env file. `bun test --isolate` puts it back.
Start,
// process.env.TZ = value
Assignment,
};

// Sets the time zone of the process from a TZ value: a zone name, ":name", or a POSIX value of whole hours such as "MSK-3".
void applyTimeZoneFromEnv(JSC::VM&, const WTF::String& value, TimeZoneWriter);

// worker_threads SHARE_ENV: a `process.env` whose reads/writes/enumeration go
// through the SharedEnvStore of the tree its global belongs to.
JSC::JSValue createSharedEnvironmentVariablesMap(Zig::GlobalObject* globalObject);
Expand Down
11 changes: 2 additions & 9 deletions src/jsc/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3329,16 +3329,9 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor)
thisObject->visitAdditionalChildrenInGCThread<Visitor>(visitor);
}

extern "C" bool JSGlobalObject__setTimeZone(JSC::JSGlobalObject* globalObject, const EncodedSlice* timeZone)
extern "C" void JSGlobalObject__setTimeZone(JSC::JSGlobalObject* globalObject, const EncodedSlice* timeZone)
{
auto& vm = JSC::getVM(globalObject);

if (WTF::setTimeZoneOverride(Zig::toString(*timeZone))) {
Bun::resetDateCachesAfterTimeZoneChange(vm);
return true;
}

return false;
Bun::applyTimeZoneFromEnv(JSC::getVM(globalObject), Zig::toString(*timeZone), Bun::TimeZoneWriter::Start);
}

extern "C" void JSGlobalObject__clearTerminationException(JSC::JSGlobalObject* globalObject)
Expand Down
3 changes: 1 addition & 2 deletions src/jsc/modules/BunJSCModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -684,12 +684,11 @@ JSC_DEFINE_HOST_FUNCTION(functionSetTimeZone, (JSGlobalObject * globalObject, Ca
String timeZoneName = callFrame->argument(0).toWTFString(globalObject);
RETURN_IF_EXCEPTION(scope, {});

if (!WTF::setTimeZoneOverride(timeZoneName)) {
if (!Bun::setProcessTimeZone(vm, timeZoneName)) {
throwTypeError(globalObject, scope,
makeString("Invalid timezone: \""_s, timeZoneName, "\""_s));
return {};
}
Bun::resetDateCachesAfterTimeZoneChange(vm);
WTF::Vector<char16_t, 32> buffer;
WTF::getTimeZoneOverride(buffer);
WTF::String timeZoneString(buffer.span());
Expand Down
4 changes: 1 addition & 3 deletions src/runtime/cli/repl_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,9 +270,7 @@ impl<'a, 'r> ReplRunner<'a, 'r> {
// Set timezone if specified
// SAFETY: transpiler.env is a valid *mut Loader set during VM init.
if let Some(tz) = unsafe { (*vm.transpiler.env).get(b"TZ") } {
if !tz.is_empty() {
let _ = vm.global().set_time_zone(&EncodedSlice::from_bytes(tz));
}
vm.global().set_time_zone(&EncodedSlice::from_bytes(tz));
}

Ok(())
Expand Down
7 changes: 2 additions & 5 deletions src/runtime/cli/run_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1152,11 +1152,8 @@ Full documentation is available at <magenta>https://bun.com/docs/cli/run<r>
// matching upstream Bun. `.env` files are loaded by
// `configure_defines` above, so `$TZ` set in one is honored.
if let Some(tz) = vm.env_loader().get(b"TZ") {
if !tz.is_empty() {
let _ = vm
.global()
.set_time_zone(&bun_core::EncodedSlice::from_bytes(tz));
}
vm.global()
.set_time_zone(&bun_core::EncodedSlice::from_bytes(tz));
}
Comment thread
robobun marked this conversation as resolved.
Resolved

// SAFETY: `vm.log` set in `init`; `b.env` is the long-lived
Expand Down
7 changes: 2 additions & 5 deletions src/runtime/cli/test_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2017,11 +2017,8 @@ impl TestCommand {
tz_name = tz;
}

if !tz_name.is_empty() {
_ = vm
.global()
.set_time_zone(&EncodedSlice::from_bytes(tz_name));
}
vm.global()
.set_time_zone(&EncodedSlice::from_bytes(tz_name));
if vm.test_isolation_enabled {
vm.test_isolation_state.time_zone = Some(Box::from(tz_name));
vm.test_isolation_state.proxy_env = Some(
Expand Down
Loading
Loading