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)
Unfortunately DateTime does not support timezones natively, as suggested by jamesdlin you will have to use a 3rd party package such as timezone.
dependencies:
timezone: any
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.
import 'package:timezone/standalone.dart' as tz;
final detroit = tz.getLocation('America/Detroit');
TZDateTime classimport '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).
I want to share this answer if you dont use any package. Just Use this extension so that you will get this below output.
extension TimeZoneExtension on Object {
DateTime _convertTimeDateTime() {
DateTime dateTimeObject = DateTime.parse(this.toString());
return dateTimeObject;
}
// Get your LocalTimeZone
getLocalTimeZone() {
return _convertTimeDateTime().toLocal();
}
// Get UTC TimeZone
getUtcTimeZone() {
return _convertTimeDateTime().toUtc();
}
// Get Local TimerZoneOffset (eg:6)
getTimeZoneOffSet() {
int timeZoneOffset =
_convertTimeDateTime().toLocal().timeZoneOffset.inHours;
return timeZoneOffset;
}
//Now If you add UTC timeZone with Local TimeZoneOffset
DateTime get dateTimeAfterOffset => _convertTimeDateTime().add(
Duration(
hours: int.parse(getTimeZoneOffSet().toString()),
),
);
}
final date = DateTime(2024, 2, 12, 10, 30);
print("Date is:: ${date}");
print("Date in UTC :: ${date.getUtcTimeZone()}"); // true
print("Date in Local :: ${date.getLocalTimeZone()}");
print(
"Now Convert this your view Dateform :${date.dateTimeAfterOffset.formattedDateString(format: AppConstant.E_MM_D_HH_MM.key)}");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With