From 528a63eee15499903d79f4220df83c10af232434 Mon Sep 17 00:00:00 2001 From: Ali Ghahremani Date: Sun, 4 Aug 2024 17:14:29 +0330 Subject: [PATCH] feat: factory function 'fromMilliseconds' added (#24) * feat: factory function 'fromMilliseconds' added * fix: timezone problem failing tests --- lib/src/gregorian/gregorian_date.dart | 6 ++++++ lib/src/jalali/jalali_date.dart | 6 ++++++ test/shamsi_date_test.dart | 28 +++++++++++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/lib/src/gregorian/gregorian_date.dart b/lib/src/gregorian/gregorian_date.dart index 230e0c6..92d3e18 100644 --- a/lib/src/gregorian/gregorian_date.dart +++ b/lib/src/gregorian/gregorian_date.dart @@ -162,6 +162,12 @@ class Gregorian extends Date { ); } + /// Create a Gregorian date from milliseconds since epoch + factory Gregorian.fromMillisecondsSinceEpoch(int milliseconds) { + return Gregorian.fromDateTime( + DateTime.fromMillisecondsSinceEpoch(milliseconds)); + } + /// Get Gregorian date for now factory Gregorian.now() { return Gregorian.fromDateTime(DateTime.now()); diff --git a/lib/src/jalali/jalali_date.dart b/lib/src/jalali/jalali_date.dart index 490a52a..0916bad 100644 --- a/lib/src/jalali/jalali_date.dart +++ b/lib/src/jalali/jalali_date.dart @@ -167,6 +167,12 @@ class Jalali extends Date { ); } + /// Create a Jalali date from milliseconds since epoch + factory Jalali.fromMillisecondsSinceEpoch(int milliseconds) { + return Jalali.fromDateTime( + DateTime.fromMillisecondsSinceEpoch(milliseconds)); + } + /// Get Jalali date for now factory Jalali.now() { return Gregorian.now().toJalali(); diff --git a/test/shamsi_date_test.dart b/test/shamsi_date_test.dart index 2f803db..b9b8aaf 100644 --- a/test/shamsi_date_test.dart +++ b/test/shamsi_date_test.dart @@ -2449,6 +2449,34 @@ void main() { expect(Gregorian(2119, 3, 21), Jalali(1498)); expect(true, Jalali(1498).isLeapYear()); }); + + test('Gregorian FromMilliseconds Test Cases', () { + const millis = 1722319497219; + final timezone = DateTime.now().timeZoneOffset; + final gdt = Gregorian.fromMillisecondsSinceEpoch( + millis - timezone.inMilliseconds); // defusing timezone + expect(gdt.year, 2024); + expect(gdt.month, 7); + expect(gdt.day, 30); + expect(gdt.hour, 6); + expect(gdt.minute, 4); + expect(gdt.second, 57); + expect(gdt.millisecond, 219); + }); + + test('Jalali FromMilliseconds Test Cases', () { + const millis = 1722319497219; + final timezone = DateTime.now().timeZoneOffset; + final jdt = Jalali.fromMillisecondsSinceEpoch( + millis - timezone.inMilliseconds); // defusing timezone + expect(jdt.year, 1403); + expect(jdt.month, 5); + expect(jdt.day, 9); + expect(jdt.hour, 6); + expect(jdt.minute, 4); + expect(jdt.second, 57); + expect(jdt.millisecond, 219); + }); } /// Mock Gregorian