Skip to content

Commit d85efb3

Browse files
committed
feat(nextcloud): add date time utils
Signed-off-by: Nikolas Rimikis <leptopoda@users.noreply.github.com>
1 parent 9e99779 commit d85efb3

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/// Common methods to work with [DateTime] data.
2+
extension DateTimeUtils on DateTime {
3+
/// Constructs a new [DateTime] instance
4+
/// with the given [secondsSinceEpoch].
5+
///
6+
/// If [isUtc] is false then the date is in the local time zone.
7+
///
8+
/// The constructed [DateTime] represents
9+
/// 1970-01-01T00:00:[secondsSinceEpoch]Z in the given
10+
/// time zone (local or UTC).
11+
/// ```dart
12+
/// final newYearsDay =
13+
/// DateTimeUtils.fromSecondsSinceEpoch(1641031200, isUtc:true);
14+
/// print(newYearsDay); // 2022-01-01 10:00:00.000Z
15+
/// ```
16+
static DateTime fromSecondsSinceEpoch(int secondsSinceEpoch, {bool isUtc = false}) {
17+
final millisecondsSinceEpoch = secondsSinceEpoch * Duration.millisecondsPerSecond;
18+
19+
return DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch, isUtc: isUtc);
20+
}
21+
22+
/// The number of seconds since the "Unix epoch" 1970-01-01T00:00:00Z (UTC).
23+
///
24+
/// This value is independent of the time zone.
25+
///
26+
/// This value is at most
27+
/// 8,640,000,000,000s (100,000,000 days) from the Unix epoch.
28+
/// In other words: `secondsSinceEpoch.abs() <= 8640000000000`.
29+
int get secondsSinceEpoch => millisecondsSinceEpoch ~/ Duration.millisecondsPerSecond;
30+
}

packages/nextcloud/lib/utils.dart

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/// This library contains various utility methods for working with nextcloud APIs.
2+
library;
3+
4+
export 'src/utils/date_time.dart';
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import 'package:nextcloud/src/utils/date_time.dart';
2+
import 'package:test/test.dart';
3+
4+
void main() {
5+
test('DateTimeUtils', () {
6+
final date = DateTime.utc(2016, 6, 2, 23, 53, 45, 243, 234);
7+
8+
expect(date.secondsSinceEpoch, 1464911625);
9+
expect(date.microsecondsSinceEpoch, 1464911625243234);
10+
11+
expect(DateTimeUtils.fromSecondsSinceEpoch(1464911625, isUtc: true), date.copyWith(millisecond: 0, microsecond: 0));
12+
expect(DateTimeUtils.fromSecondsSinceEpoch(1464911625, isUtc: true).microsecondsSinceEpoch, 1464911625000000);
13+
});
14+
}

0 commit comments

Comments
 (0)