On my local machine this date DateTime(2021, 10, 27, 00, 00, 00)
is at GMT 4
When I push this code to our remote server, the same date is interpreted with GMT 2, because the remote server is located in the GMT 2 timezone, so the code behaves differently.
I know I could make use of the DateTime.utc
constructor but I want this date to be input manually and always follow GMT 4.
So the solution is to change the local of the remote server to GMT 4 too. But how to do that in the dart context only ? (not system wide)
CodePudding user response:
Unfortunately DateTime
does not support timezones natively, as suggested by jamesdlin you will have to use a 3rd party package such as timezone.
How to use
Step 1: Install the package
dependencies:
timezone: any
Step 2: Initialize the library
main.dart
import 'package:timezone/data/latest.dart' as tz;
void main() {
WidgetsFlutterBinding.ensureInitialized();
tz.initializeTimeZones();
runApp(MyApp());
}
Note: It is recommended when you import this package to add as tz
.
Step 3: Define your wanted timezone
import 'package:timezone/standalone.dart' as tz;
final detroit = tz.getLocation('America/Detroit');
Step 4: Use the TZDateTime
class
import 'package:timezone/standalone.dart' as tz;
final localizedDt = tz.TZDateTime.from(DateTime.now(), detroit);
You can use the following constructor for TZDateTime
depending of your needs:
TZDateTime(...)
TZDateTime.utc(...)
TZDateTime.local(...)
TZDateTime.now(...)
TZDateTime.fromMillisecondsSinceEpoch(...)
TZDateTime.fromMicrosecondsSinceEpoch(...)
TZDateTime.from(...)
You can also directly parse your date from a formatted string by using TZDateTime.parse(Location location, String formattedString)
.