Skip to content

[WIP] feat: Add DateTimeSecondsSinceEpoch #59975

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 2 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
20 changes: 20 additions & 0 deletions sdk/lib/core/date_time.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1007,3 +1007,23 @@ extension DateTimeCopyWith on DateTime {
);
}
}

/// Adds methods for seconds since epoch to [DateTime] objects.
@Since("3.8")
extension DateTimeSecondsSinceEpoch on DateTime {
Copy link

@EArminjon EArminjon Mar 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello,

Small question, why not making the change like other factories line 415 ?

external DateTime.fromMillisecondsSinceEpoch(
  int millisecondsSinceEpoch, {
  bool isUtc = false,
});
...

external DateTime.fromMicrosecondsSinceEpoch(
  int microsecondsSinceEpoch, {
  bool isUtc = false,
});

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this extension useful as a getter has been set inside the DateTime class ?

/// This value is independent of the time zone.
///
/// The value is at most 8,640,000,000,000 seconds (100,000,000 days)
/// from the Unix epoch.
/// In other words: `secondsSinceEpoch.abs() <= 8640000000000`.
int get secondsSinceEpoch {
return this.millisecondsSinceEpoch ~/ Duration.millisecondsPerSecond;
}

/// Creates a [DateTime] instance from seconds since epoch.
static DateTime fromSecondsSinceEpoch(int seconds) {
return DateTime.fromMillisecondsSinceEpoch(
seconds * Duration.millisecondsPerSecond,
);
}
}
20 changes: 20 additions & 0 deletions tests/corelib/date_time_seconds_since_epoch_test.dart
Original file line number Diff line number Diff line change
@@ -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);
}