I have to display in a Flutter app, the time (HH:MM) of a flight in the local time of the country where the flight is taking off or landing. And NOT according to the timezone of the mobile device
So, how can I get the specific time format (HH:MM) of a Timezone, knowing that I got 2 different TZ format (according to source). Either such as Europe/London or could be +04:00
I have seen possibly 2 libraries timezone or time_machine but don't know if it is good fit
Many thanks
Unfortunately, the DateTime class of Dart only supports UTC and the local timezone. I suggest using the following third party package:
https://pub.dev/packages/timezone
It supports time zones:
import 'package:timezone/standalone.dart' as tz;
Future<void> setup() async {
await tz.initializeTimeZone();
var detroit = tz.getLocation('America/Detroit');
var now = tz.TZDateTime.now(detroit);
}
Related
i want to get time now in Cairo using timezone package independent of device date
but unfortunately it gives me the device date time . i don't know where is the error hope some one help me . the code below
DateTime returnCommonDate(){
tz.initializeTimeZones();
final egyptTimeZone = tz.getLocation('Africa/Cairo');
final now = tz.TZDateTime.now(egyptTimeZone);
print("=========================this is egypt time ${now}");
return now;
}
Is there any way to check if the system DateTime is correct or not in Flutter? I tried searching for APIs which provide current DateTime, but the problem with timezones happens again. What is the solution for this? (I want to do something like WhatsApp. which is, don't give chatting access if system DateTime is wrong)
you can use ntp plugin
var nowInternet = await NTP.now();
var now = DateTime.now();
print(nowInternet);
print(now);
//check diff is grater than 1 minute
if (nowInternet.difference(now).inMinutes < 1){
//good
}
simple solution, use unix epoch time
print(DateTime.now().millisecondsSinceEpoch);
I currently have the following use case:
User receives a date in UTC from the backend
This date is transformed into local time for displaying purposes
The date is displayed in different inputs. One input for date and other for time
User can select time independently
The date should be sent back to the backend in UTC format as well
I'm not very experienced with time zones and I'm getting beaten by trying to allow the user to set up only the time (or date) in a datetime field.
My pseudo code is the following:
When receiving the from backend simply convert the date to show it to the user, making the orignal date stay in UTC
When the user picks the hour and minute (all in one action) use setHours and setMinutes from date-fns library
Use native toISOString() to set in models
Code so far [playground]:
import { utcToZonedTime, format } from "date-fns-tz";
import { setHours, setMinutes } from "date-fns";
const UTCStringdate = "2022-04-06T10:00:00.000000Z";
const userTimezone = "Asia/Bangkok";
const localizedTime = utcToZonedTime(UTCStringdate, userTimezone);
// Prints the correct information
// 10:00 in UTC is equal to 17:00 in Bangkok
console.log(format(localizedTime, "HH:mm"));
// Now I expext to set only the `minutes` and `hours`
// to this `localizedTime` so that I can update the backend
const [hours, minutes] = "10:30".split(":");
// Somewhere over here the `setHours` and `setMinutes`
// is turning the Date object into my own timezone
// and not using `Asia/Bangkok` timezone anymore
let newTime = setHours(localizedTime, hours);
newTime = setMinutes(newTime, minutes);
// Now I expect to print 17:30 since we only
// set up 30 minutes forward than the original one
// but it ends up printing 10:30
console.log(format(newTime, 'HH:mm'));
I understand that somewhere along the way (most likely in setHours and setMinutes) the date-fns library turns back the localizedTime back into my own timezone, completely ruining the idea of turning the Asia/Bangkok time into UTC.
Questions
First, is this the best approach to manipulate only the time part of a date when considering timezones? If not, anyone can point me to articles? I wasn't able to find anything on the topic
Second, how can I use setHours and setMinutes and still maintain the timezone?
There are no multiple time zones in JavaScript. There is UTC and there is your local one. What date-fns-tz does, is adjusting the time to the chosen user time zone. In your example, you can see this when printing both the original and the localized time
const utcTime = new Date(UTCStringdate);
console.log(utcTime.toISOString()); // -> 2022-04-06T10:00:00.000Z
console.log(localizedTime.toISOString()); // -> 2022-04-06T14:00:00.000Z
To solve your issue, convert UTC time to users time and let the user to adjust hours and minutes in his local time zone. After that, convert the time object back to UTC using zonedTimeToUtc
newTime = zonedTimeToUtc(newTime, userTimezone);
and then use newTime.toISOString() to send it back to the server.
console.log(newTime.toISOString());
I am trying to retrieve the timezone abbreviations of the local time zone by using the following code.
private func getLocalTimezone() -> String {
guard let localTimezone = TimeZone.current.abbreviation() else {
return ""
}
return localTimezone
}
But when I am in Indian time zone I am always getting GMT+5:30 where I need it as IST. Its coming correctly when I am in CST or PST. Can anyone please suggest a way to reach to the solution for this issue.
Thanks a lot in advance
This is because time zone abbreviations are locale sensitive. IST only means India Standard Time (Asia/Kolkata) in India. In other parts of the world, it could mean Israel Standard Time, or Irish Standard/Summer Time. Here's a site that shows you the list of abbreviations. You can see for yourself how ambiguous they can be.
This is why abbreviation() takes into account the region of your phone, i.e. this setting:
abbreviation() will give you "IST" if your device's region is India. If your phone is somewhere else, it shows "GMT+5:30" because that is the safest, most unambiguous option.
If you want it to output IST no matter where your device is, you need to hard code this by creating a dictionary of time zone identifiers to abbreviations that you want. There is a built in abbreviationDictionary that goes the other way - abbreviations to identifiers. You can search it, and it will work for IST (Asia/Kolkata), but might not work for whatever other time zone that you are interested in.
let abbreviation = TimeZone.abbreviationDictionary
.first(where: { $1 == TimeZone.current.identifier })?.key
and I'm not sure whether the contents of this dictionary will stay the same in future versions of iOS. Use it at your own risk.
Is there a way of getting the first day of the week from device info or locale in Flutter? I use some libraries for which it has to be manually set, so I need to get it somehow. Or maybe, at least, these is even a library you might know which returns first day of the week by locale code?
You can use subtract method to get first day of the week according to user's device locate
DateTime today = DateTime.now();
_firstDayOfTheweek = today.subtract(new Duration(days: today.weekday));
Or you can do that with material localization and get it from context
MaterialLocalizations.of(context).firstDayOfWeekIndex;