diff --git a/sdk/lib/core/date_time.dart b/sdk/lib/core/date_time.dart index ffa349fa61a8..7af07027d705 100644 --- a/sdk/lib/core/date_time.dart +++ b/sdk/lib/core/date_time.dart @@ -399,6 +399,25 @@ class DateTime implements Comparable { static const int _maxMicrosecondsSinceEpoch = _maxMillisecondsSinceEpoch * Duration.microsecondsPerMillisecond; + /// Constructs a new [DateTime] instance + /// with the given [secondsSinceEpoch]. + /// + /// /// If [isUtc] is false then the date is in the local time zone. + /// + /// The constructed [DateTime] represents + /// 1970-01-01T00:00:00Z + [secondsSinceEpoch] seconds in the given + /// time zone (local or UTC). + /// ```dart + /// final newYearsDay = + /// DateTime.fromSecondsSinceEpoch(1641031200, isUtc:true); + /// print(newYearsDay); // 2022-01-01 10:00:00.000Z + /// ``` + @Since("3.8") + external DateTime.fromSecondsSinceEpoch( + int secondsSinceEpoch, { + bool isUtc = false, + }); + /// Constructs a new [DateTime] instance /// with the given [millisecondsSinceEpoch]. /// @@ -788,6 +807,17 @@ class DateTime implements Comparable { bool isUtc, ); + /// The number of seconds since + /// the "Unix epoch" 1970-01-01T00:00:00Z (UTC). + /// + /// This value is independent of the time zone. + /// + /// This value is at most + /// 86,400,000,000s. (100,000,000 days) from the Unix epoch. + /// In other words: `secondsSinceEpoch.abs() <= 86400000000`. + @Since("3.8") + external int get secondsSinceEpoch; + /// The number of milliseconds since /// the "Unix epoch" 1970-01-01T00:00:00Z (UTC). /// diff --git a/tests/corelib/date_time_seconds_since_epoch_test.dart b/tests/corelib/date_time_seconds_since_epoch_test.dart new file mode 100644 index 000000000000..b124a45f220c --- /dev/null +++ b/tests/corelib/date_time_seconds_since_epoch_test.dart @@ -0,0 +1,20 @@ +// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import "package:expect/expect.dart"; + +/// Tests `DateTime.secondsSinceEpoch`. + +testSecondsSinceEpoch(DateTime original, int expectedSeconds) { + final result = original.secondsSinceEpoch; + Expect.equals(expectedSeconds, result); +} + +void main() { + final epoch = DateTime.utc(1970, 1, 1); + final oneHourLater = DateTime.utc(1970, 1, 1, 1); // 3600 seconds since epoch + + testSecondsSinceEpoch(epoch, 0); + testSecondsSinceEpoch(oneHourLater, 3600); +}