Skip to content

Commit

Permalink
feat(nextcloud): add date time utils
Browse files Browse the repository at this point in the history
Signed-off-by: Nikolas Rimikis <leptopoda@users.noreply.github.com>
  • Loading branch information
Leptopoda committed Mar 11, 2024
1 parent 9e99779 commit d85efb3
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
30 changes: 30 additions & 0 deletions packages/nextcloud/lib/src/utils/date_time.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/// Common methods to work with [DateTime] data.
extension DateTimeUtils on DateTime {
/// 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:[secondsSinceEpoch]Z in the given
/// time zone (local or UTC).
/// ```dart
/// final newYearsDay =
/// DateTimeUtils.fromSecondsSinceEpoch(1641031200, isUtc:true);
/// print(newYearsDay); // 2022-01-01 10:00:00.000Z
/// ```
static DateTime fromSecondsSinceEpoch(int secondsSinceEpoch, {bool isUtc = false}) {
final millisecondsSinceEpoch = secondsSinceEpoch * Duration.millisecondsPerSecond;

return DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch, isUtc: 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
/// 8,640,000,000,000s (100,000,000 days) from the Unix epoch.
/// In other words: `secondsSinceEpoch.abs() <= 8640000000000`.
int get secondsSinceEpoch => millisecondsSinceEpoch ~/ Duration.millisecondsPerSecond;
}
4 changes: 4 additions & 0 deletions packages/nextcloud/lib/utils.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/// This library contains various utility methods for working with nextcloud APIs.
library;

export 'src/utils/date_time.dart';
14 changes: 14 additions & 0 deletions packages/nextcloud/test/utils_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import 'package:nextcloud/src/utils/date_time.dart';
import 'package:test/test.dart';

void main() {
test('DateTimeUtils', () {
final date = DateTime.utc(2016, 6, 2, 23, 53, 45, 243, 234);

expect(date.secondsSinceEpoch, 1464911625);
expect(date.microsecondsSinceEpoch, 1464911625243234);

expect(DateTimeUtils.fromSecondsSinceEpoch(1464911625, isUtc: true), date.copyWith(millisecond: 0, microsecond: 0));
expect(DateTimeUtils.fromSecondsSinceEpoch(1464911625, isUtc: true).microsecondsSinceEpoch, 1464911625000000);
});
}

0 comments on commit d85efb3

Please sign in to comment.