How to get current timezone region (tz database name) in Flutter
Asked Answered
R

12

51

I am new to flutter and my rest api takes current timezone as Europe/london. I don't know to get current timezone in flutter. There is a question in stackoverflow about this topic but no user gave the answer.

Flutter Timezone (as ZoneId)

Can anyone guide me, how can i get the current timezone in flutter using dart.

Rinaldo answered 14/1, 2019 at 7:39 Comment(4)
For name you can use - DateTime.now().timeZoneName Barbee
I don't want this format, my api takes Europe/london timezone's format. but this code give me The Europe Standard timeRinaldo
DO NOT USE DateTime.now().timeZoneName! Timezone abbreviations are ambiguous. CST for example can mean Central Standard Time, Cuba Standard Time, or China Standard Time. There's a wiki page that explains more (en.wikipedia.org/wiki/List_of_time_zone_abbreviations). It's not ISO 8601 compliant, and mostly deprecated for modern use. Confused as to why the Dart team makes these timezones more accessible than the tz timezone regions.Pulpboard
@MehulRanpara - While probably not an ideal solution, if you use the Windows operating system, DateTime.now().timeZoneName should return the full time zone name (api.dart.dev/stable/2.16.1/dart-core/DateTime/timeZoneName.html).Pulpboard
T
37

DateTime is the default class give use timezone and time offset both required to solve timezone related issue.

 DateTime dateTime = DateTime.now();
 print(dateTime.timeZoneName);
 print(dateTime.timeZoneOffset);

Output:

1. India

timeZoneName: IST
timeZoneOffset: 5:30:00.000000

2. America/Los_Angeles

timeZoneName: PST
timeZoneOffset: -8:00:00.000000

timezone list: https://help.syncfusion.com/flutter/calendar/timezone

Tuque answered 5/1, 2021 at 15:1 Comment(7)
dateTime.timeZoneName returns only "+5:30" not ISTOverlarge
Just Checked: It returns Abbreviated String. DateTime.now().timeZoneNameManchukuo
dateTime timeZoneName returns +0430 for me, I can't get the abbreviationImaginative
@Imaginative go to darpad.dev and try this code void main() { print(DateTime.now().timeZoneName); }Manchukuo
OP wants a solution that gives the tz timezone region, so DateTime.now().timeZoneName and DateTime.now().timeZoneOffset are not solutions.Pulpboard
The timeZoneName (which gives an abbreviation on all systems except Windows) and timeZoneOffset when combined might be enough to answer the OPs question. But one would need to build a map, that uses the timeZoneName and timeZoneOffset to pick the correct tz timezone region.Pulpboard
"Mitteleuropäische Zeit" is the timeZoneName in germany. And that is completely useless if not insanely ridiculous!Toxinantitoxin
C
19

There is a great library for this: https://pub.dev/packages/flutter_native_timezone

Cephalo answered 23/5, 2019 at 15:1 Comment(1)
I'm using flutter_timezone instead of flutter_native_timezone because the author of flutter_native_timezone seems to have stopped developing. Source: github.com/pinkfish/flutter_native_timezone/issues/…Rootlet
M
14

/// The time zone name. /// /// This value is provided by the operating system and may be an /// abbreviation or a full name.
/// /// In the browser or on Unix-like systems commonly returns abbreviations, /// such as "CET" or "CEST". On Windows returns the full name, for example /// "Pacific Standard Time".
external String get timeZoneName;

/// The time zone offset, which /// is the difference between local time and UTC. /// /// The offset is positive for time zones east of UTC. /// /// Note, that JavaScript, Python and C return the difference between UTC and /// local time. Java, C# and Ruby return the difference between local time and /// UTC.
external Duration get timeZoneOffset;

DateTime.now().timeZoneName

If time instance is in UTC.

timeInstance.toLocal().timeZoneName

Moreover,

/// The DateTime class does not provide internationalization. /// To internationalize your code, use /// the intl package.

OR

To get timezone in Europe/Moscow format: From here: Using flutter_native_timezone

final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
print(currentTimeZone); // Europe/Moscow
Manchukuo answered 26/4, 2021 at 1:6 Comment(1)
this package is good but not working on windowsEustazio
E
6
// Use this

Map timezoneNames = {
  0: 'UTC',
  10800000: 'Indian/Mayotte',
  3600000: 'Europe/London',
  7200000: 'Europe/Zurich',
  -32400000: 'Pacific/Gambier',
  -28800000: 'US/Alaska',
  -14400000: 'US/Eastern',
  -10800000: 'Canada/Atlantic',
  -18000000: 'US/Central',
  -21600000: 'US/Mountain',
  -25200000: 'US/Pacific',
  -7200000: 'Atlantic/South_Georgia',
  -9000000: 'Canada/Newfoundland',
  39600000: 'Pacific/Pohnpei',
  25200000: 'Indian/Christmas',
  36000000: 'Pacific/Saipan',
  18000000: 'Indian/Maldives',
  46800000: 'Pacific/Tongatapu',
  21600000: 'Indian/Chagos',
  43200000: 'Pacific/Wallis',
  14400000: 'Indian/Reunion',
  28800000: 'Australia/Perth',
  32400000: 'Pacific/Palau',
  19800000: 'Asia/Kolkata',
  16200000: 'Asia/Kabul',
  20700000: 'Asia/Kathmandu',
  23400000: 'Indian/Cocos',
  12600000: 'Asia/Tehran',
  -3600000: 'Atlantic/Cape_Verde',
  37800000: 'Australia/Broken_Hill',
  34200000: 'Australia/Darwin',
  31500000: 'Australia/Eucla',
  49500000: 'Pacific/Chatham',
  -36000000: 'US/Hawaii',
  50400000: 'Pacific/Kiritimati',
  -34200000: 'Pacific/Marquesas',
  -39600000: 'Pacific/Pago_Pago'
};

data[DateTime.now().timeZoneOffset.inMilliseconds] // Ex : Indian/Mayotte
Edessa answered 2/10, 2022 at 13:19 Comment(2)
Please update the formatting so it is easier to use. Consider using code blocks. Makes it easier for people that stumble across this answer to it more easily.Waterborne
how is this approach working regarding swaps of summer/winter times in those countries where it is present?Emmie
M
2

https://pub.dartlang.org/packages/timezone with https://docs.flutter.io/flutter/dart-core/DateTime/timeZoneOffset.html might work for you.

You can always make native functionality available to Flutter by building an https://flutter.io/docs/development/packages-and-plugins/developing-packages#developing-plugin-packages

https://github.com/flutter/flutter/issues/12531 is also somewhat related.

Mooney answered 14/1, 2019 at 7:46 Comment(3)
i do not understand and little bit confuse about how to get the timezone. Can You plz give me the snippet of getting current timezone ? @Gunter ZochbauerRinaldo
The package docs should explain it. I don't have a concrete snippet.Heavenly
@GünterZöchbauer The docs of timezone don't explain it. In fact timezone is incapable of getting the current timezone as it will use UTC as local timezone until you set it yourself, which apparently is a problem in itself and its solution leads to @AlexanderKrol's answer.Baseless
P
0

Dart does not provide a tz timezone for the platform directly, however one can use the following two properties and a mapping to determine the tz timezone.


(1) The DateTime.now().timeZoneName property gives a timezone abbreviation (on Windows it gives a full name). This abbreviation alone is not enough to determine a time zone. For example, CST can mean Central Standard Time, Cuba Standard Time, China Standard Time, etc.

(2) The DateTime.now().timeZoneOffset property gives a UTC offset, which vertical spans multiple timezones. This alone is not enough to determine a timezone.


To determine the tz timezone, use both the DateTime.now().timeZoneName and DateTime.now().timeZoneOffset properties, and map to the appropriate tz timezone.

Example below (which could be created as a Flutter package):

String timeZone = DateTime.now().timeZoneName.toString();
String timeZoneOffset = DateTime.now().timeZoneOffset.toString();

String tzTimeZoneName = '';
String timeZoneName = '';

if (
  (timeZone == 'CST' || timeZone == 'CST ( Central Standard Time )') &&
  timeZoneOffset == '-6:00:00.00-0.0'
) {
  tzTimeZoneName = 'America/Chicago';
  timeZoneName = 'Central Standard Time';
}

These two pages can be used to create a full mapping: https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Note: This mapping technique can also be used to convert the timezone abbreviation into the full name timezone (on non-Window systems). For example CST, to "Central Standard Time". I also think the Dart team, could have patched this on non-Window systems, as they have both the timezone abbreviation and the UTC offset. 🤷🏻‍♂️

Pulpboard answered 28/2, 2022 at 22:44 Comment(0)
C
0

add this in your pub

flutter_native_timezone: ^2.0.0

import 'package:flutter/services.dart';

 void getTimeZone() async{
    const MethodChannel channel = MethodChannel('flutter_native_timezone');
    final String? localTimezone = await channel.invokeMethod("getLocalTimezone");
    print(localTimezone);
  }

output -> Asia/Karachi

Cupbearer answered 20/1, 2023 at 6:11 Comment(0)
E
0

You can get this by using flutter_timezone.

 static Future<String> getCurrentTimezone() async {
    final String currentTimeZone = await 
    FlutterTimezone.getLocalTimezone();
    return currentTimeZone;
  }

Output:

Europe/london
Exsanguine answered 5/2 at 8:18 Comment(0)
V
0

Here is the Updated Version of flutter_native_timezone Package.

It works Perfectly Fine

By this Code you can get the Local TimeZone which is included in tz DataBase: final String currentTimeZone = await FlutterTimezone.getLocalTimezone();

I am Using Version: flutter_timezone: ^1.0.8 // It works for me

Voltaic answered 16/7 at 6:31 Comment(1)
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewMelvin
D
-1
  var date = DateTime.now().toIso8601String().split(".")[0];
  if(DateTime.now().timeZoneOffset.isNegative){
    date += "-";
  } else {
    date += "+";
  }
  final timeZoneSplit = DateTime.now().timeZoneOffset.toString().split(":");

  var hour = int.parse(timeZoneSplit[0]);
  if(hour < 10){
    date += "0${timeZoneSplit[0]}";
  }
  date += ":" + timeZoneSplit[1];
  print(date);

This will work and this will give something like 2021-07-15T19:28:25+05:30. Here 5:30 is IST. Which should be good.

Decreasing answered 15/7, 2021 at 14:23 Comment(0)
L
-1
import 'package:intl/intl.dart';

DateTime startDate = DateTime.now().toLocal();
var date = DateFormat.yMMMd().format(startDate);
Lutetium answered 10/2, 2022 at 6:49 Comment(1)
Your answer could be improved with additional supporting information. Please edit your answer to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Aarau
F
-3

Maybe useful for someone, I'm using:

String formatDateToStringWithTimeZone(DateTime date) {
  var dur = date.timeZoneOffset;
  if (dur.isNegative)
    return "${DateFormat("y-MM-ddTHH:mm:ss").format(date)}-${dur.inHours.toString().padLeft(2, '0')}:${(dur.inMinutes - (dur.inHours * 60)).toString().padLeft(2, '0')}";
  else
    return "${DateFormat("y-MM-ddTHH:mm:ss").format(date)}+${dur.inHours.toString().padLeft(2, '0')}:${(dur.inMinutes - (dur.inHours * 60)).toString().padLeft(2, '0')}";
}
Foretoken answered 28/3, 2021 at 18:50 Comment(1)
What if the offset 1:30, wouldn't be a bug in the above code then?Curbing

© 2022 - 2024 — McMap. All rights reserved.