Code Monkey home page Code Monkey logo

time_machine's Introduction

logo-dtm

The Dart Time Machine is a date and time library for Flutter, Web, and Server with support for timezones, calendars, cultures, formatting and parsing.

Time Machine provides an alternative date and time API over Dart Core. For comparision:

Dart Core API

  • Duration - an amount of time with microsecond precision
  • DateTime - a unique point on the utc_timeline or a point in localtime with microsecond or millisecond precision

Time Machine API

  • Time - an amount of time with nanosecond precision
  • Instant - a unique point on the utc_timeline
  • LocalTime - the time on the clock
  • LocalDate - the date on the calendar
  • LocalDateTime - a location on the clock and calendar
  • Period - amount of time on the clock and calendar
  • Offset - the timezone offset from the utc_timeline
  • DateTimeZone - a mapping between the utc_timeline, and clock and calendar locations
  • ZonedDateTime - a unique point on the utc_timeline and a location on the clock and calendar
  • Culture - formatting and parsing rules specific to a locale

Time Machine's Goals

  • Flexibility - multiple representations of time to fit different use cases
  • Consistency - works the same across all platforms
  • Testable - easy to test your date and time dependent code
  • Clarity - clear, concise, and intuitive
  • Easy - the library should do the hard things for you

The last two/three? are generic library goals.

Time Machine is a port of Noda Time; use it for all your .NET needs.

Current TZDB Version: 2022a

Example Code:

// Sets up timezone and culture information
await TimeMachine.initialize();
print('Hello, ${DateTimeZone.local} from the Dart Time Machine!\n');

var tzdb = await DateTimeZoneProviders.tzdb;
var paris = await tzdb["Europe/Paris"];

var now = Instant.now();

print('Basic');
print('UTC Time: $now');
print('Local Time: ${now.inLocalZone()}');
print('Paris Time: ${now.inZone(paris)}\n');

print('Formatted');
print('UTC Time: ${now.toString('dddd yyyy-MM-dd HH:mm')}');
print('Local Time: ${now.inLocalZone().toString('dddd yyyy-MM-dd HH:mm')}\n');

var french = await Cultures.getCulture('fr-FR');
print('Formatted and French ($french)');
print('UTC Time: ${now.toString('dddd yyyy-MM-dd HH:mm', french)}');
print('Local Time: ${now.inLocalZone().toString('dddd yyyy-MM-dd HH:mm', french)}\n');

print('Parse French Formatted ZonedDateTime');

// without the 'z' parsing will be forced to interpret the timezone as UTC
var localText = now
    .inLocalZone()
    .toString('dddd yyyy-MM-dd HH:mm z', french);

var localClone = ZonedDateTimePattern
    .createWithCulture('dddd yyyy-MM-dd HH:mm z', french)
    .parse(localText);

print(localClone.value);

VM

selection_116

Flutter

selection_117

Web (Dart2JS and DDC)

selection_118

All unit tests pass on DartVM and DartWeb (just Chrome at this time). Tests have been run on preview versions of Dart2, but the focus is on DartStable, and they are not run before every pub publish. The public API is stabilizing -- mostly focusing on taking C# idiomatic code and making it Dart idiomatic code, so I wouldn't expect any over zealous changes. This is a preview release -- but, I'd feel comfortable using it. (Author Stamp of Approval!)

Documentation was ported, but some things changed for Dart and the documentation is being slowly updated (and we need an additional automated formatting pass).

Don't use any functions annotated with @internal. As of v0.3 you should not find any, but if you do, let me know.

Todo (before v1):

  • Port Noda Time
  • Unit tests passing in DartVM
  • Dartification of the API
    • First pass style updates
    • Second pass ergonomics updates
    • Synchronous TZDB timezone provider
    • Review all I/O and associated classes and their structure
    • Simplify the API and make the best use of named constructors
  • Non-Gregorian/Julian calendar systems
  • Text formatting and Parsing
  • Remove XML tags from documentation and format them for pub (human second pass still needed)
  • Implement Dart4Web features
  • Unit tests passing in DartWeb
  • Fix DartDoc Formatting
  • Create simple website with examples (at minimal a good set of examples under the examples directory)

External data: Timezones (TZDB via Noda Time) and Culture (ICU via BCL) are produced by a C# tool that is not included in this repository. The goal is to port all this functionality to Dart, the initial tool was created for bootstrapping -- and guaranteeing that our data is exactly the same thing that Noda Time would see (to ease porting).

Future Todo:

  • Produce our own TSDB files
  • Produce our own Culture files
  • Benchmarking & Optimizing Library for Dart

Flutter Specific Notes

You'll need this entry in your pubspec.yaml.

# The following section is specific to Flutter.
flutter:
  assets:
    - packages/time_machine/data/cultures/cultures.bin
    - packages/time_machine/data/tzdb/tzdb.bin

Your initialization function will look like this:

import 'package:flutter/services.dart';

WidgetsFlutterBinding.ensureInitialized();

// TimeMachine discovers your TimeZone heuristically (it's actually pretty fast).
await TimeMachine.initialize({'rootBundle': rootBundle});

Once flutter gets Isolate.resolvePackageUri functionality, we'll be able to merge VM and the Flutter code paths and no asset entry and no special import will be required. It would look just like the VM example.

Or with: https://pub.dartlang.org/packages/flutter_native_timezone

import 'package:flutter/services.dart';

// you can get Timezone information directly from the native interface with flutter_native_timezone
await TimeMachine.initialize({
  'rootBundle': rootBundle,
  'timeZone': await Timezone.getLocalTimezone(),
});

DDC Specific Notes

toString on many of the classes will not propagate patternText and culture parameters. Instant and ZonedDateTime currently have toStringDDC functions available to remedy this.

This also works:

dynamic foo = new Foo();
var foo = new Foo() as dynamic;
(foo as dynamic).toString(patternText, culture);

We learned in Issue:33876 that dynamic code uses a different flow path. Wrapping your code as dynamic will allow toString() to work normally. It will unfortunately ruin your intellisense.

See Issue:33876 for more information. The fix exists, now we just wait for it to hit a live build.

toStringDDC instead of toStringFormatted to attempt to get a negative contagion coefficient. If you are writing on DartStable today and you need some extra string support because of this bug, let me know.

Update: Dart 2.0 stable did not launch with the fix. Stable release windows are 6 weeks. Hopefully we get the fix in the next release (second half of September).

time_machine's People

Contributors

dana-ferguson avatar jonasbark avatar jonaswanke avatar malmi avatar polrk avatar rich-j avatar stevealexander avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

time_machine's Issues

Compile error when run on mobile

Flutter crash report; please file at https://github.com/flutter/flutter/issues.

command

flutter run

exception

ProcessException: ProcessException: Process "/usr/bin/xcrun" exited abnormally:
An error was encountered processing the command (domain=IXUserPresentableErrorDomain, code=1):
This app could not be installed at this time.
Could not hardlink copy /Users/kv/Library/Developer/CoreSimulator/Devices/3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C/data/Containers/Bundle/Application/B77C4569-51F2-4B02-8B1D-A567C778F2D3/Runner.app to /Users/kv/Library/Developer/CoreSimulator/Devices/3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C/data/Library/Caches/com.apple.mobile.installd.staging/temp.ERpbay/extracted/Payload/Runner.app with manifest /Users/kv/Library/Developer/CoreSimulator/Devices/3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C/data/Library/Caches/com.apple.mobile.installd.staging/temp.ERpbay/extracted/com.apple.deltainstallcommands.com.example.flutterExample
Could not hardlink copy /Users/kv/Library/Developer/CoreSimulator/Devices/3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C/data/Containers/Bundle/Application/B77C4569-51F2-4B02-8B1D-A567C778F2D3/Runner.app to /Users/kv/Library/Developer/CoreSimulator/Devices/3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C/data/Library/Caches/com.apple.mobile.installd.staging/temp.ERpbay/extracted/Payload/Runner.app with manifest /Users/kv/Library/Developer/CoreSimulator/Devices/3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C/data/Library/Caches/com.apple.mobile.installd.staging/temp.ERpbay/extracted/com.apple.deltainstallcommands.com.example.flutterExample
Underlying error (domain=MIInstallerErrorDomain, code=8):
Could not hardlink copy /Users/kv/Library/Developer/CoreSimulator/Devices/3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C/data/Containers/Bundle/Application/B77C4569-51F2-4B02-8B1D-A567C778F2D3/Runner.app to /Users/kv/Library/Developer/CoreSimulator/Devices/3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C/data/Library/Caches/com.apple.mobile.installd.staging/temp.ERpbay/extracted/Payload/Runner.app with manifest /Users/kv/Library/Developer/CoreSimulator/Devices/3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C/data/Library/Caches/com.apple.mobile.installd.staging/temp.ERpbay/extracted/com.apple.deltainstallcommands.com.example.flutterExample
Command: /usr/bin/xcrun simctl install 3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C /Users/kv/Downloads/time_machine-master/example/flutter_example/build/ios/iphonesimulator/Runner.app

#0      runCheckedAsync (package:flutter_tools/src/base/process.dart:259:7)
<asynchronous suspension>
#1      SimControl.install (package:flutter_tools/src/ios/simulators.dart:128:16)
#2      IOSSimulator._setupUpdatedApplicationBundle (package:flutter_tools/src/ios/simulators.dart:415:31)
<asynchronous suspension>
#3      IOSSimulator.startApp (package:flutter_tools/src/ios/simulators.dart:315:15)
<asynchronous suspension>
#4      FlutterDevice.runHot (package:flutter_tools/src/resident_runner.dart:371:54)
#5      _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:77:64)
#6      _rootRunUnary (dart:async/zone.dart:1132:38)
#7      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#8      _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
#9      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
#10     Future._propagateToListeners (dart:async/future_impl.dart:668:32)
#11     Future._complete (dart:async/future_impl.dart:473:7)
#12     _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#13     _AsyncAwaitCompleter.complete.<anonymous closure> (dart:async-patch/async_patch.dart:33:20)
#14     _rootRun (dart:async/zone.dart:1120:38)
#15     _CustomZone.run (dart:async/zone.dart:1021:19)
#16     _CustomZone.runGuarded (dart:async/zone.dart:923:7)
#17     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
#18     _rootRun (dart:async/zone.dart:1124:13)
#19     _CustomZone.run (dart:async/zone.dart:1021:19)
#20     _CustomZone.runGuarded (dart:async/zone.dart:923:7)
#21     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
#22     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#23     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#24     _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:116:13)
#25     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:173:5)

flutter doctor

�[32m[✓]�[39m Flutter (Channel stable, v1.7.8+hotfix.4, on Mac OS X 10.14.6 18G87, locale en-US)
    �[32m•�[39m Flutter version 1.7.8+hotfix.4 at /Users/kv/working/flutter
    �[32m•�[39m Framework revision 20e59316b8 (4 weeks ago), 2019-07-18 20:04:33 -0700
    �[32m•�[39m Engine revision fee001c93f
    �[32m•�[39m Dart version 2.4.0

�[32m[✓]�[39m Android toolchain - develop for Android devices (Android SDK version 29.0.0)
    �[32m•�[39m Android SDK at /Users/kv/Library/Android/sdk
    �[32m•�[39m Android NDK location not configured (optional; useful for native profiling support)
    �[32m•�[39m Platform android-29, build-tools 29.0.0
    �[32m•�[39m Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    �[32m•�[39m Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
    �[32m•�[39m All Android licenses accepted.

�[32m[✓]�[39m Xcode - develop for iOS and macOS (Xcode 10.3)
    �[32m•�[39m Xcode at /Applications/Xcode.app/Contents/Developer
    �[32m•�[39m Xcode 10.3, Build version 10G8
    �[32m•�[39m CocoaPods version 1.7.5

�[32m[✓]�[39m iOS tools - develop for iOS devices
    �[32m•�[39m ios-deploy 1.9.4

�[32m[✓]�[39m Android Studio (version 3.4)
    �[32m•�[39m Android Studio at /Applications/Android Studio.app/Contents
    �[32m•�[39m Flutter plugin version 37.0.1
    �[32m•�[39m Dart plugin version 183.6270
    �[32m•�[39m Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)

�[33m[!]�[39m IntelliJ IDEA Ultimate Edition (version 2019.2)
    �[32m•�[39m IntelliJ at /Applications/IntelliJ IDEA.app
    �[31m✗�[39m Flutter plugin not installed; this adds Flutter specific functionality.
    �[31m✗�[39m Dart plugin not installed; this adds Dart specific functionality.
    �[32m•�[39m For information about installing plugins, see
      https://flutter.dev/intellij-setup/#installing-the-plugins

�[32m[✓]�[39m Connected device (1 available)
    �[32m•�[39m iPhone Xʀ • 3413F5AE-064D-49B6-A6F8-C6A2C09D8E0C • ios • com.apple.CoreSimulator.SimRuntime.iOS-12-4 (simulator)

�[33m!�[39m Doctor found issues in 1 category.

Package uses device time instead of the timezones actual time

**So I am trying to get Africa/Nairobi's time because my app needs a country's exact time to work, and if the user's device is 2 minutes infront or behind, it won't work. I personally needs the exact time for my API's timestamp.

So I tried to use this package but it still prints out the device time and calculates the time according to the device time instead of the timezone's time. Why is that?

Below are the functions that I am using :**

/* Time Machine testing */

Future timeMachineMain() async {
try {
// Sets up timezone and culture information
await TimeMachine.initialize({
'rootBundle': rootBundle,
});
print('Hello, ${DateTimeZone.local} from the Dart Time Machine!\n');

  var tzdb = await DateTimeZoneProviders.tzdb;
  var paris = await tzdb['Europe/Paris'];
  var nrb = await tzdb['Africa/Nairobi'];

  var now = Instant.now();

  print('Basic');
  print('UTC Time: $now');
  print('Local Time: ${now.inLocalZone()}');
  print('Paris Time: ${now.inZone(paris)}\n');
  print('nrb Time: ${now.inZone(nrb)}\n');

  print('Formatted');
  print('UTC Time: ${now.toString('dddd yyyy-MM-dd HH:mm')}');
  print(
      'Local Time: ${now.inLocalZone().toString('dddd yyyy-MM-dd HH:mm')}\n');

  var french = await Cultures.getCulture('fr-FR');
  print('Formatted and French ($french)');
  print('UTC Time: ${now.toString('dddd yyyy-MM-dd HH:mm', french)}');
  print(
      'Local Time: ${now.inLocalZone().toString('dddd yyyy-MM-dd HH:mm', french)}\n');

  print('Parse French Formatted ZonedDateTime');

  // without the 'z' parsing will be forced to interpret the timezone as UTC
  var localText =
      now.inLocalZone().toString('dddd yyyy-MM-dd HH:mm z', french);

  var localClone = ZonedDateTimePattern.createWithCulture(
          'dddd yyyy-MM-dd HH:mm z', french)
      .parse(localText);

  print(localClone.value);
} catch (error, stack) {
  print(error);
  print(stack);
}

}

How can I achieve to get the time without using the local device time??

Cannot compile time_machine on with latest flutter stable channel 1.22.6

I cannot build with latest flutter stable channel 1.22.6, neither with the version 0.9.16 nor with the master branch

../../../development/flutter/.pub-cache/git/time_machine-7fbfd2fc84fd8ee6a6be4cf16e429d64d3a4df3f/lib/src/calendar_system.dart:8:2: Error: Getter not found: 'internal'.
@internal
 ^^^^^^^^
../../../development/flutter/.pub-cache/git/time_machine-7fbfd2fc84fd8ee6a6be4cf16e429d64d3a4df3f/lib/src/calendar_system.dart:8:2: Error: This can't be used as metadata; metadata should be a reference to a compile-time constant variable, or a call to a constant constructor.
@internal
 ^
../../../development/flutter/.pub-cache/git/time_machine-7fbfd2fc84fd8ee6a6be4cf16e429d64d3a4df3f/lib/src/zoneddatetime.dart:18:2: Error: Getter not found: 'internal'.
@internal
 ^^^^^^^^

....

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 1.22.6, on Mac OS X 10.15.7 19H114 darwin-x64, locale en-CH)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 12.4)

Tried the following versions

  #time_machine: ^0.9.16
  time_machine:
    git:
      url: https://github.com/Dana-Ferguson/time_machine

Many thanks for suggestions to fix it.

LocalDate methods name

minusPeriod(Period) -> plus(Period)
minusDate -> no plus
plusDays, etc -> no minus

Is there a reason for those non symmetric names ?

[Web] Get stuck at initialize call

Hi,

Is there any additional setup required to run this package in web?
It is working fine in the mobile app, but always get stuck at initialize call when running in flutter web.

Any help is appreciated.

How to handle system language changes

How do I handle system language changes in Flutter?

Changing the language in my Android device's settings does not change the Culture.current, and therefore not the date and time format.

What I'm currently doing is saving the Cultures my app supports and retrieving the correct one using Localizations.localeOf(context).

Is this the correct way? Or is there a better solution?

Any plans to support json_serializable builder

Currently https://pub.dev/packages/json_serializable returns an unsupported type error:

[SEVERE] json_serializable:json_serializable on lib/oxxxx_model.dart:
Error running JsonSerializableGenerator
Could not generate `fromJson` code for `foundingDate`.
None of the provided `TypeHelper` instances support the defined type.
package:origins_app/origin_model.dart:60:19
   ╷
60 │   final LocalDate foundingDate;
   │                   ^^^^^^^^^^^^
   ╵

Controller

Hello
I've tried your plugin and works great
I have lots of meetings in my calendar and it takes 2/3 seconds to create event calendar for controller
Do you have any idea how to wait for timetable because I received a null controller exception during these seconds before calendar appears ?

May be a wait screen will be Great

Regars

Regis

Flutter web release builds missing data

Time Machine works great for Flutter iOS/Android and even AngularDart (one web platform). I'm sure you're aware that there's a new web platform that is looking quite promising - Flutter web. Time Machine works great with Flutter web debug builds that use DDC and serve files from packages.

However, our Flutter web release build threw the cryptic exception Instance of 'minified:me'. We traced this exception back to Time Machine failing to retrieve the tzdb.json data file. Underlying this issue is that Flutter web release builds don't have and/or correctly fetch the data files. This isn't particularly a Time Machine failing since Flutter web is a new platform and the "rules" are still being defined.

We found that we could copy the Time Machine data files to the expected location. The expected location for tzdb.json is http://myserver.com/packages/time_machine/data/tzdb/tzdb.json with the other time zone and culture files under the data directory too. We also configured our CI web build to copy these data files.

So - what's the issue? We appreciate that Time Machine for the web doesn't just download the 1MB of Flutter asset .bin files and instead only fetches the needed zone and culture data. We also found that the Flutter team is still trying to resolve issues regarding package assets (e.g. flutter/flutter#27802). Maybe the above "workaround" is good enough and just needs to be documented.

en_GB culture file doesn't include day of week in its long format date pattern

The en_GB culture file doesn't include the day of the week in its long date format:

  print(LocalDate.today().toString('D', await Cultures.getCulture('en-US')));
  > Friday, September 13, 2019
  print(LocalDate.today().toString('D', await Cultures.getCulture('en-AU')));
  > Friday, 13 September 2019
  print(LocalDate.today().toString('D', await Cultures.getCulture('en-GB')));
  > 13 September 2019

en_GB.bin has dd MMMM yyyy vs dddd, MMMM d, yyyy in en-US.bin.

Just wondering if that's an oddity in the data source that the culture file is generated from, or might indicate a problem with the conversion process? Based on ICU locales I'd expect day to be include in the GB locale too (see e.g. http://www.localeplanet.com/icu/en-GB/)

Updated web build tools no longer will build web apps that use time_machine

In a web project, upgrading the build_web_compilers dev_dependency from: ^1.2.1 to ^2.1.0 causes the build (e.g. webdev serve) to not create the web application, instead we get this warning in the build:

[WARNING] build_web_compilers:entrypoint on web/main.dart: Skipping compiling webapp|web/main.dart with ddc because some of its
transitive libraries have sdk dependencies that not supported on this platform:

time_machine|lib/src/timezones/tzdb_io.dart
time_machine|lib/src/utility/binary_writer.dart
resource|lib/src/resolve.dart

https://github.com/dart-lang/build/blob/master/docs/faq.md#how-can-i-resolve-skipped-compiling-warnings

[INFO] Running build completed, took 25.2s

When we revert to build_web_compilers: ^1.2.1 our web project builds and runs. The suggested "help link" doesn't seem to provide relevant advice.

Looking at the file tzdb_io.dart we see import 'dart:io';. This package is not supported on the web and seems to be the "sdk dependency" that the warning is referring to. It also doesn't seem to be used in that file, so a simple line deletion removes that source file from the above warning.

The file binary_writer.dart also imports dart:io but it is using io package functionality. The timezones directory has files that depend on binary_writer.dart but seem to not be needed for web support (they seem to be used for creating the tzdb file). Could this part of the system be restructured to not be a dependency for read-only (e.g. web and Flutter) uses?

It's not clear what the resolution will be for the resource package dependency. There are recent issues filed/updated: dart-archive/resource#35 and also dart-lang/sdk#37153. These seem to suggest removing support for the web altogether - although it seems that time_machine may not use the resource package for the web either.

Cannot initialize on latest flutter dev, iOS simulator

I get an error using timemachine in a flutter app. I've tested this so far on an iOS simulator.

What happens is, when I initialize TimeMachine, it is unable to load the culture from the rootbundle.

      await TimeMachine.initialize({
        'rootBundle': rootBundle
      });

The error is:

Unable to load asset: packages/time_machine/data/cultures/-.bin

This occurs because io.Platform.localeName is returning _ (see flutter/flutter#23241 ), and the TimeMachine logic in vm.dart doesn't deal with this well.

    var cultureId = io.Platform.localeName?.split('.')?.first?.replaceAll('_', '-') ?? 'en-US';
    var culture = await Cultures.getCulture(cultureId);
$ flutter doctor -v
[✓] Flutter (Channel master, v0.10.1-pre.77, on Mac OS X 10.13.6 17G2307, locale
    en-GB)
    • Flutter version 0.10.1-pre.77 at /Users/steve/code/flutter
    • Framework revision 5193affb27 (2 hours ago), 2018-10-18 04:15:02 -0400
    • Engine revision cc2ec365b7
    • Dart version 2.1.0-dev.7.1.flutter-b99bcfd309

[✓] Android toolchain - develop for Android devices (Android SDK 28.0.1)
    • Android SDK at /Users/steve/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling
      support)
    • Platform android-28, build-tools 28.0.1
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_152-release-1024-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.0)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.0, Build version 10A255
    • ios-deploy 2.0.0
    • CocoaPods version 1.5.3

[✓] Android Studio (version 3.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 26.0.1
    • Dart plugin version 173.4700
    • Java version OpenJDK Runtime Environment (build
      1.8.0_152-release-1024-b01)

[✓] VS Code (version 1.27.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 2.18.0

[✓] Connected device (1 available)
    • iPhone X • EF563F7A-675E-4CF8-AFFF-E518AF44A1F2 • ios • iOS 12.0
      (simulator)

• No issues found!

NoSuchMethodError: The getter 'id' was called on null

This was reported via Sentry.io, with an app that is using flutter_native_timezone.

The problem is in vm.dart, line 91

    var local = timeZoneOverride != null ? await tzdb.getZoneOrNull(timeZoneOverride) : await _figureOutTimeZone(tzdb);
    // todo: cache local more directly? (this is indirect caching)
    TzdbIndex.localId = local.id;

Getting local.id fails because local is null.

I think the culprit is tzdb.getZoneOrNull that might return null.

I guess if it returns null, Perhaps timemachine should log a warning message, and then resort to _figureOutTimeZone

NanosecondTime not exposed

NanosecondTime is not exposed.

 Instant.epochTime(NanosecondTime(nanosecAsInt))

Is more descriptive than

Instant.fromEpochBigIntNanoseconds(BigInt.from(nanosecAsInt))

We can still keep current time in long 64 bit as for the next appox 260 years. After that I don't care anymore :)

Difference between date in February and March 2021

I'm trying to get the difference between the below dates, but the result is 44min 50sec. Am I doing something wrong?

     //time_machine: ^0.9.15

      final start = LocalDateTime(2021, 2, 27, 4, 23, 4);
      final end = LocalDateTime(2021, 3, 1, 5, 7, 54);

Anything special to do to have dates translated in system language in Flutter app?

I'm trying to integrate this wonderful package in my Flutter project and everything is working except for the translation of LocalDate's so far.
I'm running my app on an iPad simulator where the language is French and the region is set to France, and it seems like this is recognized by other parts of the application (eg i18n_extension). But for some weird reason, LocalDate(2020, 9, 12).toString() gives me 'Saturday, 12 September 2020' instead of the 'Samedi 12 Septembre 2020' I was expecting.
Is there something special I need to do for the default language to be the system one?

Flutter build broken : Dart updated to 2.1 dev

@Dana-Ferguson Help !! build is broken

The current Dart SDK version is 2.1.0-dev.0.0.flutter-be6309690f.
Because flutter_native_timezone 1.0.0 requires SDK version >=1.9.0 <2.0.0 and no versions of flutter_native_timezone match >1.0.0 <2.0.0, flutter_native_timezone ^1.0.0 is forbidden.
So, because flutter_calender depends on flutter_native_timezone ^1.0.0, version solving failed.

Support for timezone abbreviation (EST, PDT, PST) and AM/PM

Hello,
How do I get the abbreviated timezone name, and the am/pm designation?
Dec 23, 2018 @ 08:00 AM PST

Example:
Given a start date as
DateTime start = DateTime(...);
DateTimeZone losAngeles = ...;

Instance i = Instance.dateTime(start);
print(instance.inZone(losAngeles).toString('MMM dd, yyyy @ HH:mm tt z');

I get the result as
Dec 23, 2018 @ 08:00 America/Los_Angeles

How can I formatted to the following:
``Dec 23, 2018 @ 08:00 AM PST`

How can i testing my app?

Text(LocalDateTime.now().toString()),
Text(LocalDateTime.now().toDateTimeLocal().toString()),
Text(DateTime.now().toString()),

In real device/simulator

Screenshot 2020-09-16 at 11 35 50

print(LocalDateTime.now().toString());
print(LocalDateTime.now().toDateTimeLocal().toString());
print(DateTime.now().toString());

In test file
Screenshot 2020-09-16 at 11 36 41

bug in epochArithmeticMod ?

In epochArithmeticMod in utilities.dart, there is a repeated if statement. Is it meant to be y in the second one?

/// This returns a pattern consistent with epoch (or calendar) based times
/// [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
/// [ 1,  2,  0,  1,  2, 0, 1, 2, 0, 1, 2]
int epochArithmeticMod(num x, int y) {
  if (x >= 0) return x % y;
  if (x >= 0) return x % y;
  return -(y-x)%y;
}

Readme and Dart 2

You should put this part on the bottom

dependencies: time_machine: "0.7.1"

And replace it with the last build ... I just copy/paste this and got trapped because the main bold title said Dart 2 ...

Improve documentation

I have a hard time understanding this library and can't afford to spend hours digging in the unit tests for examples. My request is to have better documentation in place.

Perhaps Documentation Driven Development helps in this?

periodSince is returning 0 on days

The following example is returning 0 on the days property:

LocalDate origin = LocalDate.dateTime(DateTime(2020, 11, 1));

LocalDate target = LocalDate.dateTime(DateTime(2021, 10, 1)); 

Period interval = target.periodSince(origin);

print("Days: ${interval.days}"); //Outputs: Days: 0

Logo Design Offer For Dart Time Machine

Hello Sir. I'm a UI/UX and Graphics Designer. who has contacted you via email last week.
Can I provide the logo contribution and make discussion about the logo on this issue?

Compile error with latest version of meta.

Upgraded to latest version of flutter and now get a compile error:

calendar_system.dart:8:2: Error: 'internal' is imported from both 'package:meta/meta.dart' and 'package:time_machine/src/time_machine_internal.dart'.

zoneddatetime.dart:18:2: Error: 'internal' is imported from both 'package:meta/meta.dart' and 'package:time_machine/src/time_machine_internal.dart'.

How to get First day of Week

In the US the first day of the week is Sunday.
I've been playing with SimpleWeekYearRule but I can't get to find the right API call.
Thanks

web issues

Hi there,
Trying to use this library with flutter web but I have some issues with it:
time_machine1

  1. I don't have this file anywhere in my project - I've looked in the open issues and saw that other people have those files.
  2. The get request tries to get the file from the root of the domain instead of the root of the web project which is:https://mydoamin.com/ironclic/.

This is my configuration:
flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, 1.22.0-12.1.pre, on Mac OS X 10.15.6 19G2021, locale
    en-IL)
 
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 12.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.0)
[✓] VS Code (version 1.49.1)
[✓] Connected device (2 available)

pubspec.yaml:

dependencies:
  time_machine: ^0.9.13

flutter:
  uses-material-design: true

  assets:
    - assets/images/
    - assets/icons/
    - assets/icon/
    - assets/translations/
    - packages/time_machine/data/cultures/cultures.bin
    - packages/time_machine/data/tzdb/tzdb.bin

build/web structure:
image

Thanks for the help!

Time.toDuration is broken

Run this:

import 'package:time_machine/time_machine.dart';

main() async {
  await TimeMachine.initialize();
  Duration d = Duration(seconds: 20);
  print('Duration.inSeconds = ${d.inSeconds}');
  Time t = Instant.now().timeUntil(Instant.now().add(Time.duration(d)));
  print('Time.inSeconds = ${t.inSeconds}');
  print('Time.toDuration.inSeconds = ${t.toDuration.inSeconds}');
}

Output is:

Duration.inSeconds = 20
Time.inSeconds = 20
Time.toDuration.inSeconds = 0

The problem seems to be in lib/src/duration.dart

  Duration get toDuration =>
      new Duration(
          microseconds: millisecondOfSecond * TimeConstants.microsecondsPerMillisecond
              + _nanosecondsInterval ~/ TimeConstants.nanosecondsPerMicrosecond);

This should be _milliseconds instead of millisecondOfSecond.

Changing this leads to the following output:

Duration.inSeconds = 20
Time.inSeconds = 20
Time.toDuration.inSeconds = 20

New instance

Hi Bro,
I want to create ZonedDateTime with timezone asia/seoul +9

  • Input: "2019-08-18 00:00:00"
  • Output I want: ZonedDateTime("2019-08-18 00:00:00" ).utc() => "2019-08-17 15:00:00"

How to do that with this lib?

Continue supporting VM processing without Flutter

PR #52 effectively makes Flutter a requirement for non-web use (web support uses different code). The PR extended the non-web platform checks that require a Flutter rootBundle from isIOS, isAndroid, isFuchsia to now also include isMacOS, isWindows, isLinux. This list effectively makes all non-web code require Flutter. This breaks testing of our common library that still supports AngularDart.

Yes, probably all new users will be using Flutter so the default path of requiring a rootBundle is reasonable. We still need some way to use _VirtualMachineIO() for testing without Flutter. How about an initialization flag useVirtualMachineIO?

In the initialize() function of vm.dart:

if (args['useVirtualMachineIO'] == true) {
  PlatformIO.local = _VirtualMachineIO();
} else {
  if (args['rootBundle'] == null) throw Exception("Pass in the rootBundle from 'package:flutter/services.dart';");
  PlatformIO.local = _FlutterMachineIO(args['rootBundle']);
}

This initialization code will allow any VM platform to opt-in to use the original non Flutter IO.

DateTime conversion fails with date prior to epoch

Hi,

Maybe I'm missing something but it seems to be impossible to use LocalDateTime.dateTime to convert a date prior to epoch into a LocalDateTime : The ns variable contains a negative number and so the assert in LocalTime._(int nanoseconds) fails

Here is my fix proposal :

factory LocalDateTime.dateTime(DateTime dateTime, [CalendarSystem calendar]) {
    int ns;
    int days;

    if (Platform.isWeb) {
      var ms = dateTime.millisecondsSinceEpoch;
      days = ms ~/ TimeConstants.millisecondsPerDay;
      ms -= days * TimeConstants.millisecondsPerDay;
      /// FIX ////
      /// if ms is < 0 then we need to remove a day
      if(ms < 0) days--;
      /// We're using % to handle negative numbers
      ns = TimeConstants.nanosecondsPerMillisecond * (ms % TimeConstants.millisecondsPerDay);
      /// FIX ///
    }
    else {
      var us = dateTime.microsecondsSinceEpoch;
      days = us ~/ TimeConstants.microsecondsPerDay;
      us -= days * TimeConstants.microsecondsPerDay;
      /// FIX ////
      if(us < 0) days--;
      ns = TimeConstants.nanosecondsPerMicrosecond * (us % TimeConstants.microsecondsPerDay) ;
      /// FIX ////
    }


    return new LocalDateTime.localDateAtTime(
        LocalDate.fromEpochDay(days, calendar),
        ILocalTime.trustedNanoseconds(ns));
  }

And the related unit test

@Test()
void FromDateTimeBeforeEpoch()
{
  LocalDateTime expected = new LocalDateTime(1966, 08, 18, 20, 53, 0);
  // for (DateTimeKind kind in Enum.GetValues(typeof(DateTimeKind)))
  DateTime x = new DateTime.utc(1966, 08, 18, 20, 53, 0); //, kind);
  LocalDateTime actual = new LocalDateTime.dateTime(x);
  expect(actual, expected);
}

Is there any way this fix could be added to the plugin ?
Thanks

TZDB data format

Hello, first, I want to thank you for porting NodaTime to Dart, and its one of the best Data/Time libraries.

I just need some clarification about the TZDB files format, I checked some parts of the code, and the files on this library seems different than the NZD format of NodaTime, am I right? and if yes, what is the limitation that pushed to using different format?

I need to understand this because I already use NodaTime in one of my apps, and I update the tzdb on the fly using the nodatime website.
If I want to implement the same thing in my apps using Flutter, I need to host the updated versions of TZDB files somewhere, so I need to understand how are generated.

Thanks in advance,

Create a time_machine_flutter package with LocalizationDelegate

I have sync Culture.current culture with Flutter localization like this

class TimeMachineDelegate extends LocalizationsDelegate<Culture> {
  Locale locale;

  @override
  bool isSupported(Locale locale) {
    return true;
  }

  @override
  Future<Culture> load(Locale locale) async {
    Culture.current = await Cultures.getCulture('${locale.languageCode}-${locale.countryCode}');
    return Culture.current;
  }

  @override
  bool shouldReload(TimeMachineDelegate old) {
    return old.locale != locale;
  }
}

I think it would be very interesting to create a package that makes easier to work time_machine with Flutter. Implementing TimeMachineDelegate inside the localizationsDelegates of MaterialApp allows to have sync the Local language everywhere across flutter :)

Probably I am missing a lot of bugs with '${locale.languageCode}-${locale.countryCode}' but I would be glad to help to do test and support all options

Consider getting timezone data from dart package "timezone"

TimeMachine provides 3 major components: library, timezone data, culture data. The library is unsurpassed in providing correct datetime calculations. I'm glad to see TimeMachine getting NNBD conversion - and a lot more cleanup (thanks @SteveAlexander).

Going forward, the main ongoing maintenance need is updating the timezone data. Just wondering if it would make sense to use the timezone data from the package https://pub.dev/packages/timezone?

Unexpected locales/cultures are not handled gracefully

With the iPhone's separation of "language" and "region" it's possible to get locales like en-CN. At present (tested on 0.9.7) it's not possible to initialise TimeMachine if the locale is not one that TimeMachine ships:

[VERBOSE-2:shell.cc(184)] Dart Error: Unhandled exception:
Unable to load asset: packages/time_machine/data/cultures/en-CN.bin
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1      _FlutterMachineIO.getBinary (package:time_machine/src/platforms/vm.dart:44:43)
<asynchronous suspension>
#2      CultureLoader.getCulture (package:time_machine/src/text/globalization/culture_io.dart:71:76)
<asynchronous suspension>
#3      Cultures.getCulture (package:time_machine/src/text/globalization/culture.dart:27:75)
<asynchronous suspension>
#4      TimeMachine.initialize (package:time_machine/src/platforms/vm.dart:97:34)
<asynchronous suspension>
#5      initialize (package:time_machine/src/platforms/vm.dart:69:22)
#6      TimeMachine.initialize (package:time_machine/time_machine.dart:100:12)
#7      main (package:------/main.dart:22:21)
<asynchronous suspension>
#8      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:289:19)
#9      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)

Flutter web initialization fails when run with IPv6 address

Under Flutter web, TimeMachine.initialize() throws SyntaxError: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL when run with an IPv6 web address such as http://[::1]:51973/.... The address [::1] is equivalent to IPv4 loopback 127.0.0.1 (aka localhost). Why use an IPv6 address? A recent change to either Flutter or IntelliJ now opens a local Chrome browser with the IPv6 address. Note - a simple workaround is to change the address to localhost.

I traced the error to the web.dart file _resolveUri routine called from getJson line 87. The getJson value of resource is http://[::1]:51973/packages/time_machine/data/tzdb/tzdb.json which is a correct URI - I can enter that in a browser and fetch the file. The value returned by _resolveUri and given to the readAsString URI parameter starts with http://::1:51973/packages/.... Note the missing [ ] in the URI host.

Flutter 1.14.6 • channel beta • https://github.com/flutter/flutter.git 
Framework • revision fabeb2a16f (3 weeks ago) • 2020-01-28 07:56:51 -0800
Tools • Dart 2.8.0 (build 2.8.0-dev.5.0 fc3af737c7)

This may possibly be the cause for issue #27 - they didn't give enough information to know.

Exception: Pass in the rootBundle from 'package:flutter/services.dart';

I was looking at the Time Machine docs as well as the given example and this is my code:

Future<void> main() async {
  setUp();
  runApp(new App());
}

Future<void> setUp() async {
  print('TimeZone!');
  
  await TimeMachine.initialize({
    rootBundle: rootBundle,
  });

  print("Hello, ${DateTimeZone.local} from the Dart Time Machine!\n");
  var tzdb = await DateTimeZoneProviders.tzdb;
  var timeZoneAmsterdam = await tzdb['Europe/Amsterdam'];
}

But I am getting this error:

Exception has occurred.
Exception: Pass in the rootBundle from 'package:flutter/services.dart';

Even though I have added this:

import 'package:flutter/services.dart';

My pubspec.yaml (minus the unnecessary):

dependencies:
  flutter:
    sdk: flutter
  time_machine: ^0.9.4

flutter:
  assets:
    - packages/time_machine/data/cultures/cultures.bin
    - packages/time_machine/data/tzdb/tzdb.bin

Is there a bug or is it just me?

$ flutter --version
Flutter 0.5.8 • channel dev • https://github.com/flutter/flutter.git
Framework • revision e4b989bf3d (8 days ago) • 2018-08-09 09:45:44 -0700
Engine • revision 3777931801
Tools • Dart 2.0.0-dev.69.5.flutter-eab492385c

flutter initialize failed

I test demo's code in Flutter 1.19.0-2.0 pre.208, i got initialize failed.

[✓] Flutter (Channel master, 1.19.0-2.0.pre, on Mac OS X 10.15.3 19D76, locale zh-Hans-CN)
    • Flutter version 1.19.0-2.0.pre at /Users/sheldon/Documents/DevelopTools/flutter
    • Framework revision bfe6d2f4e6 (3 days ago), 2020-05-29 19:08:01 -0400
    • Engine revision 4d78121a11
    • Dart version 2.9.0 (build 2.9.0-11.0.dev 6489a0c68d)

I run it in a iOS12.0 simulator, here is the error message:

#0      initialize 
package:time_machine/…/platforms/vm.dart:60
#1      TimeMachine.initialize 
package:time_machine/time_machine.dart:100
#2      example 
package:zefyr_demo/main.dart:28
#3      main 
package:zefyr_demo/main.dart:19
#4      _runMainZoned.<anonymous closure>.<anonymous closure>  (dart:ui/hooks.dart:247:25)
#5      _rootRun  (dart:async/zone.dart:1190:13)
#6      _CustomZone.run  (dart:async/zone.dart:1093:19)
#7      _runZoned  (dart:async/zone.dart:1630:10)
#8      runZonedGuarded  (dart:async/zone.dart:1618:12)
#9      _runMainZoned.<anonymous closure>  (dart:ui/hooks.dart:239:5)
#10     _startIsolate.<anonymous closure>  (dart:isolate-patch/isolate_patch.dart:301:19)
#11     _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:168:12)```

Update Installation Guide and Example.

I was really struggling to get this project up and running since the Example had no indication that the rootBundle argument must be passed to TimeMachine.initialize nor does the actual method have it as a required parameter.

Secondly, once I figured that out I struggled some more with an additional asset loading error which after much debugging I found mentioned in the API Reference that 2 assets need to be listed in pubsec.yaml, there's no mention of this in the Installation Guide.

I'm going to add the 3 main errors I was dealing with down below so that others that have similar errors can finally figure out how this library needs to be set up (until the documentation is updated), If I have the time I'll try to create a PR myself.

  • Unhandled Exception: Exception: Pass in the rootBundle from 'package:flutter/services.dart';
  • Unhandled Exception: NoSuchMethodError: The method 'getJson' was called on null.
  • Unhandled Exception: Unable to load asset: packages/time_machine/data/tzdb/tzdb.bin

For easy copy-pasting here are the solutions:

Add to pubsec.yaml:

assets:
  - packages/time_machine/data/cultures/cultures.bin
  - packages/time_machine/data/tzdb/tzdb.bin

How to Initialize TimeMachine:

await TimeMachine.initialize({
  'rootBundle': rootBundle,
});

TzdbDateTimeZoneSource.FromStream is missing

Hello! The method TzdbDateTimeZoneSource.FromStream doesn't exist in this repo at all, but it's using inside ToTzdbDateTimeZoneSource for example.

  TzdbDateTimeZoneSource ToTzdbDateTimeZoneSource() {
    var ms = new MemoryStream();
    var writer = new TzdbStreamWriter();
    writer.write(this,
        new WindowsZones("n/a", version, "n/a", <MapZone>[]), // No Windows mappings,
        new Map<String, String>(), // No additional name-to-id mappings
        BinaryWriter(ms));
    ms.position = 0;
    return TzdbDateTimeZoneSource.FromStream(ms); <<<<<<<<<<<<<<<<<<<<< is missing
  }

Please fix it.

Problems with pub [...] serve

Using pub [...] serve I get the following error messages (yes i made a clean pub get, pub serve):
[SEVERE] build_web_compilers|ddc on package:resource/resource.dartdevc.module:
Error compiling dartdevc module:resource|lib/resource.ddc.js

[error] Target of URI doesn't exist: 'io_none.dart'. (package:resource/src/resource_loader.dart, line 8, col 8)
[error] Target of URI doesn't exist: 'io_io.dart'. (package:resource/src/resource_loader.dart, line 10, col 26)

Please fix all errors before compiling (warnings are okay).
}
[...]
[SEVERE] build_web_compilers|ddc on package:time_machine/time_machine.dartdevc.module:
Error compiling dartdevc module:time_machine|lib/time_machine.ddc.js

[error] Target of URI doesn't exist: 'src/platforms/vm.dart'. (package:time_machine/time_machine.dart, line 12, col 24)

Please fix all errors before compiling (warnings are okay).
}

When I change the imports and remove the "SEVERE" ones, I can run the app. I only use LocalDate in my app.

Null safety

This is a request to add support for null safety to this package. See the migration guide for details about enabling null safety.

Hours using periodSince shows up as 0

I'm trying to get the hours since a certain date but the hours, minutes and seconds all return 0

    LocalDate a = LocalDate.today();
    LocalDate b = LocalDate.dateTime(DateTime(2020, 3, 29));
    Period diff = a.periodSince(b);
    var _months = diff.months; //6
    var _days = diff.days; //22
    var _hours = diff.hours; // 0
    var _seconds = diff.seconds; //0
    var _minutes = diff.minutes; //0
    print('${diff.toString()}'); //P6M22D

What can I do to correct this? Or did I set b incorrectly

Confusion on format vs parse

I've been going in circles, digging in the source and docs with trying code variations, and I'm not sure what i'm missing.

Problem: I have a String for a date/time with a timezone attached eg "2019-12-01 08:10 CST"

I wanted to convert this in to a DateTime, but as there's no timezone support, I'm now trying to use TimeMachine to use ZonedDateTime.

Pattern: MM-dd-yyyy HH:mm x
--> pattern is only capable of formatting, not parsing

If I change the pattern to: MM-dd-yyyy HH:mm z
--> The specified time zone identifier is not recognized

The 2nd error makes sense, as I believe 'z' means the fuller text version, eg "America/Chicago".
I failed to bookmark where I saw the formatting codes, and I'm unable to find it now (probably due to crossed eyes).

My current attempt looks like this:

    var usc = await Cultures.getCulture('en-US');
 ...
var eventPattern = ZonedDateTimePattern.createWithCulture("MM-dd-yyyy HH:mm z", usc);

I've tried createWithInvariantCulture, and many others I've forgotten.

I'm sure this is easy, but what is it I'm not seeing or understanding? I've also tried giving a DateTimeZoneProvider (var tzdb = await DateTimeZoneProviders.tzdb;), to alleviate what I understood the problem to be with the "formatter, not a parser", and that's a null DTZP.

Thank you!

DateTimeZone.local always returns UTC

Hey everyone!

I'm using this package to try to get the current ISO time zone (i.e. America/Phoenix). However, it looks like DateTimeZone.local (like shown in the readme) always returns UTC... Am I missing something?

flutter

Message with the last Flutter upgrate :

Because every version of flutter_test from sdk depends on collection 1.14.6
and time_machine >=0.8.0 depends on collection ^1.14.10, flutter_test from
sdk is incompatible with time_machine >=0.8.0.

So, because flutter_calender depends on both time_machine 0.8.2 
and flutter_test any from sdk, version solving failed.

io.Platform.localeName is C.UTF-8 on github actions server

@rich-j originally noted this issue against #50

I'm re-filing it as an issue, seeing as that PR has now been merged.

It seems that GitHub actions running on ubuntu doesn't have a valid locale defined so calling TimeMachine.initialize(); fails with:

Failed to load "test/a_test.dart": Null check operator used on a null value
  package:time_machine/src/platforms/vm.dart 99:39  TimeMachine.initialize

Lines 96-100

   // Default Culture
   var cultureId = io.Platform.localeName.split('.').first.replaceAll('_', '-');
   Culture? culture = await Cultures.getCulture(cultureId);
   ICultures.currentCulture = culture!;       // <-- the non-null assertion here fails
   // todo: remove Culture.currentCulture

explicitly assumes the culture is found. It also has a todo to possibly remove this.

On that OS, io.Platform.localeName is C.UTF-8.

A bit of research on this suggests that a reasonable thing to do for a platform locale of C is to use en.US

See the first full answer here: https://unix.stackexchange.com/questions/87745/what-does-lc-all-c-do

@rich-j do you think adding a special case here for a locale of C and using en.US would meet your needs?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.