SOLUTIONS OF ERRORS 1. http error(Unhandled Exception: Bad state: Insecure HTTP is not allowed by platform): write https instead of http 2. Uri error: get(Uri.parse("https:...")); 3. for +/- error(wrong hours for negative timezones): substring(0,3) instead of (1,3)
For those who want to experiment another time zone which has offset in minutes too, don't forget to add that too: String offset1 = data['utc_offset'].substring(1,3); String offset2 = data['utc_offset'].substring(4,6); DateTime now = DateTime.parse(datetime); now = now.add(Duration(hours: int.parse(offset1), minutes: int.parse(offset2))); print(now);
or instead of declaring two Strings 'offset1' & 'offset2' we could simply add minutes to our DateTime object to whatever timezone minutes you want to add. for example: now = now.add(Duration(hours: int.parse(offset), minutes: 30));
He actually kind of forgets there are offsets like -01:30, denoting negative offset having hours as 1 and minutes as 30. A quick fix to this, although I'm sure there are better methods around, is: String datetime = time['datetime']; List offset = time['utc_offset'].split(':').map((e) => int.parse(e)).toList(); DateTime now = DateTime.parse(datetime); now = now.add(Duration(hours: offset[0], minutes: offset[1]));
You don't need the offset anymore. The API ensures the date and time is correct at specific region. Just use the 'datetime' property and you're good to go. But if you want to use the datetime that has no offset, you can use the 'utc_datetime' property.
'datetime' still has an offset, which means when converting it to a DateTime object the time still ends up being off So, what I did was: " String datetime = data["datetime"]; datetime = datetime.substring(0, datetime.length - 6); "
@@Dogflamingo The reason that might be happening might be, the console prints the date in UTC time zone. In the video, even though the time looks correct i.e. "5:54" in London, in reality that is "5:54" in UTC which incorrect time.
You are just amazing. I never knew i will learn flutter with ease. I stopped last year as it was quite confusing, just three days i came across this videos i can code effortlessly. Many thanks bro for the good job. You are a talented and amazing code coach.
This is made unnecessarily difficult by the way the DateTime.parse() function works. The 'datetime' property actually contains the exact time you want, but includes the offset at the end. DateTime.parse() automatically adds the offset, resulting in a DateTime object that is always set to UTC. An alternate method is to just make a substring of the first 26 characters (i.e. remove the offset from the 'datetime' property) and then parse that string like so: String datetime = data['datetime']; DateTime now = DateTime.parse(datetime.substring(0,26));
07:57 This is incorrect. You have to include the sign at position 0. Otherwise for Timezones with negative (-) like Los Angeles (-08:00) it will add to the current time and the time will be incorrect. Still a great series and I love it.
There is some time zones that have a negative offset number, so the correct thing to do is to set substring(0, 3) otherwise it will only add the offset.
You have a very unique style of putting forward things. Recently stumbled upon your channel for some react concepts but ended up looking for other topics as well. Thanks for the videos.. 2 things, 1. The response from the API your referring to already has utc_datetime and datetime variable so if we had to go forward with the offset addition and subtraction method then one should use utc_datetime response variable(This is obviously for other viewers) 2. I guess offsets can be in negative as well so again for other viewers one should take into consideration the addition and subtraction symbol before the offset amount. Or rather use a library which will help you increase or decrease the datetime with relevant timezone offsets. Once again thanks for such informative videos.
Now there is an easier way to add the offset, simply by just running: `DateTime date = DateTime.parse(data["datetime"]).toLocal();` it will automatically add the offset to the date (add .toLocal() method to the DateTime object)
Cheer brother! You've helped immensely! I got a new job that required an app developed by using flutter and I was lost up until these tutorials. Bless your talented heart! You're amazing at what you do I swear. Subscribed, liked, hit the bell icon. Most definitely recommend this channel to other devs.
I'm in a timezone with a negative offset (-03:00) and you need to have the sign in front of the offset otherwise is always a positive number. The + or - in the front dosen't seems to bother the int convertion. String offset = data['utc_offset'].substring(0, 3);
You can add int sign = offset.substring(0, 1) == "+" ? 1 : -1; and then modify the now variable to be now = now.add(Duration(hours: int.parse(offset.substring(1, 3) * sign)));
For anyone having issues with `Unhandled Exception: FormatException: Unexpected character (at character 1)` What's likely failing is when we're trying to decode the body since we're assuming the body is a json format. The issue is when we retrieve the response and there was an error from the server, the body will be an html format instead and confuse the json decoder. So we can check the response's status code first, and only proceed if it's 200, otherwise it's an error and we can print it out. For my case sometimes I did get 200 and everything worked ok, but other times the response was returning 503 (Service Unavailable). This is not really our fault, just an issue on the server's side. So you can check if it's a bad response then throw or print the error: if (response.statusCode != 200) { throw("Bad response ${response.statusCode}: ${response.body}"); }
I've also had trouble with this error, but I got fix about it. The Troubleshooter of my problem is that check the get() function. By this time(2021.12.13), it's syntax is little different from the video's. you should use get(Uri.http('first argument' , 'second argument' ) instead of using get('full length of the site's location.) and the first argument is constitued only by the small alphabet and dot(.) which means it doesnt allow to be putted the slash(/). And the rest of the site's location will be placed at the second argument, also containing variable which is developer privatly make.(And also dont forget about the $ before the variable.)
If you want UTC negative offsets get the whole string included inthe + - signs when parsing offset String datetime = data['datetime']; int offset = int.parse(data['utc_offset'].substring(0, 3)); DateTime now = DateTime.parse(datetime); now = now.add(Duration(hours: offset)); print(now); }
For those who live in the North America or with a negative offset .. String symbol = data['utc_offset'].toString().substring(0,1); DateTime now = DateTime.parse(datetime); now = symbol == '-' ? now.subtract(Duration(hours: int.parse(offset))) : now.add(Duration(hours: int.parse(offset))) ; which is the same as ... if (symbol == '-') { now = now.subtract(Duration(hours: int.parse(offset))); } else { now = now.add(Duration(hours: int.parse(offset))); }
in 24 row code must be: String offset = data['utc_offset'].substring(0,3); For negative utc_offset e. g. America/Chicago = '-06:00' if you substring(0,2) you get +6
or make a function like that DateTime dateGenerate(String utcTime,String utcOffset){ var hourWithSign=num.parse(utcOffset.split('.')[0]); var minutesWithSign=num.parse(utcOffset.substring(0,1)+utcOffset.split('.')[1]); DateTime now=DateTime.parse(utcTime); now =now.add(Duration(hours: hourWithSign)); now =now.add(Duration(minutes:minutesWithSign)); print(now); }
I have found out that there may be an error when running the program with the end link, from World Time API, starting with 'http'. Rather it should start with 'https'. I had this error and could not figure out what was the issue until I came across this info.
@@levisatto8268 Yes, I found some information from StackOverflow. You can change the starting point of the world time API link to 'https' instead of using 'http'. I'm not sure if your network area has any effect on this option.
For those of you that are getting an error from the api. As of Android API 28 and iOS 9, http is not allowed anymore. You will need to add `` to your "AndroidManifest.xml" (android/app/src/debug/AndroidManifest.xml) file inside the tags. I got it working so if you have any more questions feel free to ask and I'll try to help!
Great video series. I'd love to see you cover application state management in some detail and SQL Lite usage, storing prefs in a file or via the stored_preferences package.
Very nice tutorial, it's been an absolute blast so far. On the World App thingy, I think the datetime only shows the time in our current location irrespective of the utc while the Utc_datetime shows the region we're using. My utc_offset is +01:00( which also is my country's timezone) while the datetime shows my local time. I think instead of adding the utc_offset after converting to DateTime object, i need to substract my timezone (utc_offset) from it to get London accurate time
You could also do: String dataTime = data["utc_datetime"]; String offset = data["utc_offset"].substring(0, 3); DateTime now = DateTime.parse(dataTime).add(Duration(hours: int.parse(offset))); So that if the offset is negative, it converts the offset to a negative value.
I was having a problem with some timezones, the london one was correct, but others like the México timezone were wrong. I made some research and had to change this: String offset = data['offset'].substring(1, 3); For this: String offset = data['utc_offset'].substring(0, 3); Hope this helps someone :)
Won't work. Same goes for countries with plus half hours. Fast simple solution: String offsetHours = offset.substring(0,1) + offset.substring(2,3); String offsetMin = offset.substring(0,1) + offset.substring(4,6); DateTime now = DateTime.parse(datetime); now = now.add(Duration(hours: int.parse(offsetHours), minutes: int.parse(offsetMin))); Otherwise thank you for some great tutorials Ninja!!
// You forgot main thing here or maybe you skipped for us to learn which is Adding Minutes & Subtracting if it is Negative TimeZone like -08:30 or +05:30. I've done it by trial n error. LEARNED it though. Thanks //Creating DateTime Object DateTime now = DateTime.parse(datetime); //convert to readable D & T String sign = fetchedData['utc_offset'][0]; // Knowing TimeZone + or - // Time Add or Minus based on TimeZone + or - if (sign == '+') { now = now.add(Duration( hours: int.parse(offsetHours), minutes: int.parse(offsetMins))); } else { now = now.subtract(Duration( hours: int.parse(offsetHours), minutes: int.parse(offsetMins))); } print(now);
If you get "[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Bad state: Insecure HTTP is not allowed by platform:" Just change "http" by "https".
Just a heads up. I think there is a mistake around the 7:30 mark when he says we don't need the '+' symbol. That's alright for all the locations with positive offset because no sign is the same as +ve sign. However, for locations to the west of the Prime Meridian, namely the Americas and a bit of Europe and Africa, the offset is -ve and skipping the sign would actually yield a wrong final time. Fix is straightforward, just change String offset = data['utc_offset'].substring(1, 3) to String offset = data['utc_offset'].substring(0, 3)
I believe you don't really need the offset since the data['datetime'] already has an offset at the end: e.g. 2021-03-05T05:33:46.858695+00:00 (offset). Correct me if i'm wrong, cuz I don't work with dates that often.
I think that the response includes 2 times datetime: which is user timezone calculated utc_datetime: is the UTC timezone so if we need to use DateTime object to format the time we should use utc_datetime + utc_offset but the point is that DateTime.parse is ignoring the timezone so the result is the same
Thanks brother for the tutorial. You made flutter easy for me. However, i felt our offset substring should be subString(0,3) not subString(1,3) to cater for negative offset timezones.
Bro, Z char in the end of date object means UTC time zone =(. If u print your date regarding to your time zone, u will get proper date time. But u hardly added 1 hour, so u will get date time in +2 timezone. Anyway u r awesome dude.
Removing + sign from offset prevent you of getting negative offsets which results wrong time for those locations. We need to get plus and minus signs if we want to get time based on GMT for instance (as result of this API provider is always down, returning 503 error)
At time 1:15, you share your Ip address. I don't know if you care about it, but I recommend blurring it out if you don't mind having the type of information out there.
pls i get this error whenever i tried hot reload "E/flutter ( 4312): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1) E/flutter ( 4312):
If y'all think offset method is confusing just do: String datetime = data['datetime']; DateTime now = DateTime.parse(datetime.substring(0, 26)); print(now);
The "datetime" value already contains the "utc_offset" but the parser ignores it. Switch to "utc_datetime" as it makes no difference and avoids confusion.
@@adamcierniak3902 Since the api already returned time in the requested timezone, he'd have been better off directly printing it here. Since he later uses intl library, he could've used DateFormat.parse to get the user friendly version. However, if the intent was to demo dart's DateTime - he should've used utc_datetime from the JSON response along with utc_offset for clarity. Also, since there are negative and positive time zone offsets and not all are aligned to an hour either - the parsing to add was insufficient. A note to the user there about the deficiency should've been there. DateTime is hard in general.
Any fix on how to fix this error E/flutter ( 6393): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: SocketException: OS Error: Connection timed out, errno = 110, address = jsonplaceholder.cypress.io, port = 42245 I get it after I try to access the JSON placeholder text. 10 percent of the time it works but then after I reset the error pops back up again
i don't if this is the best practice for programming or not cause i'm still new to programming in general. but for negative offset i got this to work for me. // create DateTime object DateTime now = DateTime.parse(datetime); print(data['utc_offset'].substring(0,1)); data['utc_offset'].substring(0,1) == '+' ? now = now.add(Duration(hours:int.parse(offset))) :now = now.subtract(Duration(hours:int.parse(offset)));
I know i'm probably just one more random comment here, but I, such as hundreds of people that were following the incredible tutorial that this has been, have not been able to proceed with it. as we're getting errors related to the API. I, myself, was not able to do anything past 4:10. We would reaaly apreciate ur help, Sir, if possible.
Dart DateTime objects don't carry timezone information, toLocal() always returns the date/time converted to the environment's local time. It'll use the UTC offset in the string when parsing to create a DateTime object where isUtc = true, i.e. it adds/subtracts the offset to the time then discards that information. api.dartlang.org/stable/2.6.0/dart-core/DateTime/parse.html. The "timezone" or "time_machine" packages might be helpful, or for this specific case, you could just chop off the offset before parsing to get the intended date/time representation.
E/flutter (29833): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: SocketException: Failed host lookup: 'worldtimeapi.org' (OS Error: No address associated with hostname, errno = 7) E/flutter (29833): I'm facing this error I'm not understanding what it is can anyone let me know please
@8:52 we make a request and API gives us time as 16:53:48 @9:21 we fix the mistake and API gives us time as 17:54:42 in video time, it is 29 seconds, in real time it is 54 seconds :d either api is broken or a seamless edit :d
Am following all your tutorials and its amazingly great...🔥🔥,You are a great teacher..... But it hurts when the worldtime api doesn't work anymore.... Any alternatives?🥺
Bruh, Ive been strugling for 2 hours, but i finally found another site with world time. If you want you could try, lemme know then. app.abstractapi.com/
There is this one mistake, that i found out, if we do not consider the + and - sign of utc-offset then it will always be + as we are adding the offset which will always give wrong answers to -ve utc timezones. You can google the current time like chichago current time and compare it with your result. There will be difference in it.
And what should I do when the utc_offset is negative? I've just changed the .substring(1,3) to .substring(0,3) but I want to know if it has another way. Thanks for the videos ♥
I did not see a "subtract" method in the Dart docs. In my conditional statement I inserted "-" before "int.parse(offset)", and it worked. However, I think Raphael's approach of using a wider substring is much cleaner. Thanks for the insight!
I appreciate your work and labor, but i have a problem with the data from this api or the api from the last video. no data came to the screen, only lines of did i touched the screen or not....
The course haS been great but I am getting this error when requesting the API: Exception has occurred. ClientException (Connection closed before full header was received)
This tutorial series was great, but I think we need an updated version of this. I am incredible confused now that the API website is completely different.
can still use the same, but I have another problem It will take some number of times to response, after I tried the third time only I recieved the response, but then when I hot reload again, it couldnt zzz....sometimes due to timeout and connection closed, so when u try to get the response when u request the worldtime api, it doesnt reach you and throws an error, I think just continue this tutorial playlist until exception handling
ruclips.net/video/AqsmaT1U6sQ/видео.html offset is +01 but you removed + and only took 01 What if it is -04, 04 will be added to original time which is wrong, is it?
Not the exact same extension, but if you google "Chrome JSON Viewer" the first one that pops up is "JSON Viewer" and it's what I use. It has some pretty cool display configurations.
I really liked your video, they are very helpful, I want to ask if you use a son formatted extinction that allows you to display json in your browser like in the video ?
@@ranjanpanda2586 Thank you for your feedback, yeah I share all my source code in my personal blog you will find it in my videos description and Soon I will release them into my github
Bruh, Ive been strugling for 2 hours, but i finally found another site with world time. If you want you could try, lemme know then. app.abstractapi.com/
He actually kind of forgets there are offsets like -01:30, denoting negative offset having hours as 1 and minutes as 30. A quick fix to this, although I'm sure there are better methods around, is: String datetime = time['datetime']; List offset = time['utc_offset'].split(':').map((e) => int.parse(e)).toList(); DateTime now = DateTime.parse(datetime); now = now.add(Duration(hours: offset[0], minutes: offset[1]));
You can't just remove first symbol from the offset. Offset can be negative and then you need this minus. Moreover, why converting it to an integer if it's clearly of type Time. Also, what is "non destructive"? I though types like this are called "immutable."
4:50 i swear you did that mistake on purpose to show us what could happen and explain to us the best way, you are a master in teaching
He's a legend!
Need a teacher like you.
You are the Best.
This can be the best programming channel on youtube.
Thanks! 😃 Glad you like!
Correction, this IS the best programming channel on youtube.
SOLUTIONS OF ERRORS
1. http error(Unhandled Exception: Bad state: Insecure HTTP is not allowed by platform): write https instead of http
2. Uri error: get(Uri.parse("https:..."));
3. for +/- error(wrong hours for negative timezones): substring(0,3) instead of (1,3)
Excellent!
Thanks bro! Keep helping!
can you help me with some other errors, i get
1. Too many positional arguments: 1 allowed but 2 found
2.uri error of some different type
Thanks a lot
Thanks bro
For those who want to experiment another time zone which has offset in minutes too, don't forget to add that too:
String offset1 = data['utc_offset'].substring(1,3);
String offset2 = data['utc_offset'].substring(4,6);
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: int.parse(offset1), minutes: int.parse(offset2)));
print(now);
thanks
or instead of declaring two Strings 'offset1' & 'offset2' we could simply add minutes to our DateTime object to whatever timezone minutes you want to add.
for example: now = now.add(Duration(hours: int.parse(offset), minutes: 30));
Thank you 🥺🥺
@@nitinkaushik5144 @Mr Duda thanks a lot🥺🥺
He actually kind of forgets there are offsets like -01:30, denoting negative offset having hours as 1 and minutes as 30.
A quick fix to this, although I'm sure there are better methods around, is:
String datetime = time['datetime'];
List offset =
time['utc_offset'].split(':').map((e) => int.parse(e)).toList();
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: offset[0], minutes: offset[1]));
You don't need the offset anymore. The API ensures the date and time is correct at specific region. Just use the 'datetime' property and you're good to go. But if you want to use the datetime that has no offset, you can use the 'utc_datetime' property.
Thanks so much man
'datetime' still has an offset, which means when converting it to a DateTime object the time still ends up being off
So, what I did was:
"
String datetime = data["datetime"];
datetime = datetime.substring(0, datetime.length - 6);
"
@@Dogflamingo The reason that might be happening might be, the console prints the date in UTC time zone. In the video, even though the time looks correct i.e. "5:54" in London, in reality that is "5:54" in UTC which incorrect time.
@@Dogflamingo Thank you for this, i was struggling here
You are just amazing. I never knew i will learn flutter with ease. I stopped last year as it was quite confusing, just three days i came across this videos i can code effortlessly. Many thanks bro for the good job. You are a talented and amazing code coach.
This is made unnecessarily difficult by the way the DateTime.parse() function works. The 'datetime' property actually contains the exact time you want, but includes the offset at the end. DateTime.parse() automatically adds the offset, resulting in a DateTime object that is always set to UTC. An alternate method is to just make a substring of the first 26 characters (i.e. remove the offset from the 'datetime' property) and then parse that string like so:
String datetime = data['datetime'];
DateTime now = DateTime.parse(datetime.substring(0,26));
Thanks So much!!
thx
can anyone share whole code. I am stuck as time zone link is not working and showing long error in debug console.
This is the only method that worked for me....thnx so much
I've noticed that too and was wondering why he just didn't use datetime from JSON, but here's the answer.
07:57 This is incorrect. You have to include the sign at position 0. Otherwise for Timezones with negative (-) like Los Angeles (-08:00) it will add to the current time and the time will be incorrect. Still a great series and I love it.
nice username
There is some time zones that have a negative offset number, so the correct thing to do is to set substring(0, 3) otherwise it will only add the offset.
You have a very unique style of putting forward things. Recently stumbled upon your channel for some react concepts but ended up looking for other topics as well. Thanks for the videos..
2 things,
1. The response from the API your referring to already has utc_datetime and datetime variable so if we had to go forward with the offset addition and subtraction method then one should use utc_datetime response variable(This is obviously for other viewers)
2. I guess offsets can be in negative as well so again for other viewers one should take into consideration the addition and subtraction symbol before the offset amount. Or rather use a library which will help you increase or decrease the datetime with relevant timezone offsets.
Once again thanks for such informative videos.
Thanks for the tutorials mate.
I was planning on building an app for my business for a long time, but now I can definitely do it
How did it go?
Now there is an easier way to add the offset, simply by just running:
`DateTime date = DateTime.parse(data["datetime"]).toLocal();`
it will automatically add the offset to the date
(add .toLocal() method to the DateTime object)
exactly
Cheer brother! You've helped immensely! I got a new job that required an app developed by using flutter and I was lost up until these tutorials. Bless your talented heart! You're amazing at what you do I swear.
Subscribed, liked, hit the bell icon. Most definitely recommend this channel to other devs.
The time you calculated was not in London but UTC (you get time in london and add offset to it). Anyway your videos helps me a lot :)
I'm in a timezone with a negative offset (-03:00) and you need to have the sign in front of the offset otherwise is always a positive number. The + or - in the front dosen't seems to bother the int convertion.
String offset = data['utc_offset'].substring(0, 3);
I found this out too when the time was wrong for some timezones.
This is what was messing me up, good call.
You can add
int sign = offset.substring(0, 1) == "+" ? 1 : -1;
and then modify the now variable to be
now = now.add(Duration(hours: int.parse(offset.substring(1, 3) * sign)));
@@aghiadalzein3069 no need for that, int.parse does read the sign, so just substring(0, 3) will work
i will not forget you in my prayers
For anyone having issues with `Unhandled Exception: FormatException: Unexpected character (at character 1)`
What's likely failing is when we're trying to decode the body since we're assuming the body is a json format.
The issue is when we retrieve the response and there was an error from the server, the body will be an html format instead and confuse the json decoder.
So we can check the response's status code first, and only proceed if it's 200, otherwise it's an error and we can print it out.
For my case sometimes I did get 200 and everything worked ok, but other times the response was returning 503 (Service Unavailable).
This is not really our fault, just an issue on the server's side.
So you can check if it's a bad response then throw or print the error:
if (response.statusCode != 200) {
throw("Bad response ${response.statusCode}: ${response.body}");
}
I've also had trouble with this error, but I got fix about it.
The Troubleshooter of my problem is that check the get() function.
By this time(2021.12.13), it's syntax is little different from the video's.
you should use get(Uri.http('first argument' , 'second argument' ) instead of using get('full length of the site's location.)
and the first argument is constitued only by the small alphabet and dot(.) which means it doesnt allow to be putted the slash(/).
And the rest of the site's location will be placed at the second argument, also containing variable which is developer privatly make.(And also dont forget about the $ before the variable.)
You are the real teacher ❤️❤️❤️❤️❤️❤️❤️❤️, lots of good wishes for you sir
If you want UTC negative offsets get the whole string included inthe + - signs when parsing offset
String datetime = data['datetime'];
int offset = int.parse(data['utc_offset'].substring(0, 3));
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: offset));
print(now);
}
wow....that's amazing, in android java, i need to write a big code to get response from server, boy I am in love with flutter, love you sir
ig you are talking about retrofit, using volley it's lot shorter.
@@amanpratapsingh1243 exactly
You are way better than those paid courses man!
For those who live in the North America or with a negative offset ..
String symbol = data['utc_offset'].toString().substring(0,1);
DateTime now = DateTime.parse(datetime);
now = symbol == '-' ? now.subtract(Duration(hours: int.parse(offset))) : now.add(Duration(hours: int.parse(offset))) ;
which is the same as ...
if (symbol == '-') {
now = now.subtract(Duration(hours: int.parse(offset)));
} else {
now = now.add(Duration(hours: int.parse(offset)));
}
in 24 row code must be:
String offset = data['utc_offset'].substring(0,3);
For negative utc_offset e. g. America/Chicago = '-06:00' if you substring(0,2) you get +6
Also in Western Hemisphere here, this is the right way to fix it!
or make a function like that
DateTime dateGenerate(String utcTime,String utcOffset){
var hourWithSign=num.parse(utcOffset.split('.')[0]);
var minutesWithSign=num.parse(utcOffset.substring(0,1)+utcOffset.split('.')[1]);
DateTime now=DateTime.parse(utcTime);
now =now.add(Duration(hours: hourWithSign));
now =now.add(Duration(minutes:minutesWithSign));
print(now);
}
I ended up using offset.split(":")[0] instead.
Thank you sir!
i think in your case it should be
now= now.subtract(Duration(hours: int.parse(offset)));
For those who cant get response from the run panel try to do "Hot Restart" instead of "CTRL + S".
this is the best channel for me .. thank you mate
I have found out that there may be an error when running the program with the end link, from World Time API, starting with 'http'. Rather it should start with 'https'. I had this error and could not figure out what was the issue until I came across this info.
I had the same problem, did u find the solution already?
@@levisatto8268 Yes, I found some information from StackOverflow. You can change the starting point of the world time API link to 'https' instead of using 'http'. I'm not sure if your network area has any effect on this option.
@@jlatham203 it worked, thank u!
thankyou brother you solved my error
Thank you it worked for me
For those of you that are getting an error from the api. As of Android API 28 and iOS 9, http is not allowed anymore. You will need to add `` to your "AndroidManifest.xml" (android/app/src/debug/AndroidManifest.xml) file inside the tags. I got it working so if you have any more questions feel free to ask and I'll try to help!
i did this.. but its still not working. could you help me with it please ?
@@Abhi-ng3re mind linking your gh so I can look at it. I should have the project on my gh `tbaustin` if you want to just copy my file.
Great video series. I'd love to see you cover application state management in some detail and SQL Lite usage, storing prefs in a file or via the stored_preferences package.
Very nice tutorial, it's been an absolute blast so far. On the World App thingy, I think the datetime only shows the time in our current location irrespective of the utc while the Utc_datetime shows the region we're using. My utc_offset is +01:00( which also is my country's timezone) while the datetime shows my local time. I think instead of adding the utc_offset after converting to DateTime object, i need to substract my timezone (utc_offset) from it to get London accurate time
You could also do:
String dataTime = data["utc_datetime"];
String offset = data["utc_offset"].substring(0, 3);
DateTime now = DateTime.parse(dataTime).add(Duration(hours: int.parse(offset)));
So that if the offset is negative, it converts the offset to a negative value.
thank you
Isn't the datetime property already with the offset? The "+1:00" is right there at the end of the string
I was having a problem with some timezones, the london one was correct, but others like the México timezone were wrong. I made some research and had to change this:
String offset = data['offset'].substring(1, 3);
For this:
String offset = data['utc_offset'].substring(0, 3);
Hope this helps someone :)
First, I love your videos (and accent), great work. Thank you very much!
And then just a thought: what happens if the offset is negative?
Won't work. Same goes for countries with plus half hours.
Fast simple solution:
String offsetHours = offset.substring(0,1) + offset.substring(2,3);
String offsetMin = offset.substring(0,1) + offset.substring(4,6);
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: int.parse(offsetHours), minutes: int.parse(offsetMin)));
Otherwise thank you for some great tutorials Ninja!!
@@FattigHjonen thanks for that!! really helpful
@@FattigHjonen thanks a ton
// You forgot main thing here or maybe you skipped for us to learn which is Adding Minutes & Subtracting if it is Negative TimeZone like -08:30 or +05:30. I've done it by trial n error. LEARNED it though. Thanks
//Creating DateTime Object
DateTime now = DateTime.parse(datetime); //convert to readable D & T
String sign = fetchedData['utc_offset'][0]; // Knowing TimeZone + or -
// Time Add or Minus based on TimeZone + or -
if (sign == '+') {
now = now.add(Duration(
hours: int.parse(offsetHours), minutes: int.parse(offsetMins)));
} else {
now = now.subtract(Duration(
hours: int.parse(offsetHours), minutes: int.parse(offsetMins)));
}
print(now);
String offsetHours = data['utc_offset'].substring(1, 3);
String offsetMins = data['utc_offset'].substring(4, 6);
If you get "[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Bad state: Insecure HTTP is not allowed by platform:"
Just change "http" by "https".
Thanks.
This works for me
you are freaking magician
Thank you, it works fine now
thanks, now my code running i am not any any output from print statement. can you help me, i am facing the same problem from the last video onward.
thanks, it worked
Just a heads up. I think there is a mistake around the 7:30 mark when he says we don't need the '+' symbol. That's alright for all the locations with positive offset because no sign is the same as +ve sign. However, for locations to the west of the Prime Meridian, namely the Americas and a bit of Europe and Africa, the offset is -ve and skipping the sign would actually yield a wrong final time. Fix is straightforward, just change
String offset = data['utc_offset'].substring(1, 3)
to
String offset = data['utc_offset'].substring(0, 3)
I believe you don't really need the offset since the data['datetime'] already has an offset at the end: e.g. 2021-03-05T05:33:46.858695+00:00 (offset). Correct me if i'm wrong, cuz I don't work with dates that often.
I think that the response includes 2 times
datetime: which is user timezone calculated
utc_datetime: is the UTC timezone
so if we need to use DateTime object to format the time we should use utc_datetime + utc_offset
but the point is that DateTime.parse is ignoring the timezone so the result is the same
Thank You Sir for the guidance
Stay Blessed
Thanks brother for the tutorial. You made flutter easy for me.
However, i felt our offset substring should be subString(0,3) not subString(1,3) to cater for negative offset timezones.
Bro, Z char in the end of date object means UTC time zone =(. If u print your date regarding to your time zone, u will get proper date time. But u hardly added 1 hour, so u will get date time in +2 timezone. Anyway u r awesome dude.
07:45 I think we should use "String offset = data['utc_offset'].substring(0, 3);" to account for "plus" or "minus" in front of the utc_offset data.
Best tutorials on flutter😍😃
Removing + sign from offset prevent you of getting negative offsets which results wrong time for those locations. We need to get plus and minus signs if we want to get time based on GMT for instance (as result of this API provider is always down, returning 503 error)
It does not prevent from getting the offset it just doesn't show it on screen
At time 1:15, you share your Ip address. I don't know if you care about it, but I recommend blurring it out if you don't mind having the type of information out there.
pls i get this error whenever i tried hot reload "E/flutter ( 4312): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter ( 4312):
If y'all think offset method is confusing just do:
String datetime = data['datetime'];
DateTime now = DateTime.parse(datetime.substring(0, 26));
print(now);
thank you!
Just to clarify that the worldtimeapi works just fine at the time im writing this. Cheers.
The "datetime" value already contains the "utc_offset" but the parser ignores it. Switch to "utc_datetime" as it makes no difference and avoids confusion.
Timezones
Below is a list of recognised timezones. This list is also available via the API. Check the spec for more details.
Africa/Abidjan
Africa/Accra
Africa/Algiers
Africa/Bissau
Africa/Cairo
Africa/Casablanca
Africa/Ceuta
Africa/El_Aaiun
Africa/Johannesburg
Africa/Juba
Africa/Khartoum
Africa/Lagos
Africa/Maputo
Africa/Monrovia
Africa/Nairobi
Africa/Ndjamena
Africa/Sao_Tome
Africa/Tripoli
Africa/Tunis
Africa/Windhoek
America/Adak
America/Anchorage
America/Araguaina
America/Argentina/Buenos_Aires
America/Argentina/Catamarca
America/Argentina/Cordoba
America/Argentina/Jujuy
America/Argentina/La_Rioja
America/Argentina/Mendoza
America/Argentina/Rio_Gallegos
America/Argentina/Salta
America/Argentina/San_Juan
America/Argentina/San_Luis
America/Argentina/Tucuman
America/Argentina/Ushuaia
America/Asuncion
America/Atikokan
America/Bahia
America/Bahia_Banderas
America/Barbados
America/Belem
America/Belize
America/Blanc-Sablon
America/Boa_Vista
America/Bogota
America/Boise
America/Cambridge_Bay
America/Campo_Grande
America/Cancun
America/Caracas
America/Cayenne
America/Chicago
America/Chihuahua
America/Costa_Rica
America/Creston
America/Cuiaba
America/Curacao
America/Danmarkshavn
America/Dawson
America/Dawson_Creek
America/Denver
America/Detroit
America/Edmonton
America/Eirunepe
America/El_Salvador
America/Fort_Nelson
America/Fortaleza
America/Glace_Bay
America/Goose_Bay
America/Grand_Turk
America/Guatemala
America/Guayaquil
America/Guyana
America/Halifax
America/Havana
America/Hermosillo
America/Indiana/Indianapolis
America/Indiana/Knox
America/Indiana/Marengo
America/Indiana/Petersburg
America/Indiana/Tell_City
America/Indiana/Vevay
America/Indiana/Vincennes
America/Indiana/Winamac
America/Inuvik
America/Iqaluit
America/Jamaica
America/Juneau
America/Kentucky/Louisville
America/Kentucky/Monticello
America/La_Paz
America/Lima
America/Los_Angeles
America/Maceio
America/Managua
America/Manaus
America/Martinique
America/Matamoros
America/Mazatlan
America/Menominee
America/Merida
America/Metlakatla
America/Mexico_City
America/Miquelon
America/Moncton
America/Monterrey
America/Montevideo
America/Nassau
America/New_York
America/Nipigon
America/Nome
America/Noronha
America/North_Dakota/Beulah
America/North_Dakota/Center
America/North_Dakota/New_Salem
America/Nuuk
America/Ojinaga
America/Panama
America/Pangnirtung
America/Paramaribo
America/Phoenix
America/Port-au-Prince
America/Port_of_Spain
America/Porto_Velho
America/Puerto_Rico
America/Punta_Arenas
America/Rainy_River
America/Rankin_Inlet
America/Recife
America/Regina
America/Resolute
America/Rio_Branco
America/Santarem
America/Santiago
America/Santo_Domingo
America/Sao_Paulo
America/Scoresbysund
America/Sitka
America/St_Johns
America/Swift_Current
America/Tegucigalpa
America/Thule
America/Thunder_Bay
America/Tijuana
America/Toronto
America/Vancouver
America/Whitehorse
America/Winnipeg
America/Yakutat
America/Yellowknife
Antarctica/Casey
Antarctica/Davis
Antarctica/DumontDUrville
Antarctica/Macquarie
Antarctica/Mawson
Antarctica/Palmer
Antarctica/Rothera
Antarctica/Syowa
Antarctica/Troll
Antarctica/Vostok
Asia/Almaty
Asia/Amman
Asia/Anadyr
Asia/Aqtau
Asia/Aqtobe
Asia/Ashgabat
Asia/Atyrau
Asia/Baghdad
Asia/Baku
Asia/Bangkok
Asia/Barnaul
Asia/Beirut
Asia/Bishkek
Asia/Brunei
Asia/Chita
Asia/Choibalsan
Asia/Colombo
Asia/Damascus
Asia/Dhaka
Asia/Dili
Asia/Dubai
Asia/Dushanbe
Asia/Famagusta
Asia/Gaza
Asia/Hebron
Asia/Ho_Chi_Minh
Asia/Hong_Kong
Asia/Hovd
Asia/Irkutsk
Asia/Jakarta
Asia/Jayapura
Asia/Jerusalem
Asia/Kabul
Asia/Kamchatka
Asia/Karachi
Asia/Kathmandu
Asia/Khandyga
Asia/Kolkata
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Macau
Asia/Magadan
Asia/Makassar
Asia/Manila
Asia/Nicosia
Asia/Novokuznetsk
Asia/Novosibirsk
Asia/Omsk
Asia/Oral
Asia/Pontianak
Asia/Pyongyang
Asia/Qatar
Asia/Qostanay
Asia/Qyzylorda
Asia/Riyadh
Asia/Sakhalin
Asia/Samarkand
Asia/Seoul
Asia/Shanghai
Asia/Singapore
Asia/Srednekolymsk
Asia/Taipei
Asia/Tashkent
Asia/Tbilisi
Asia/Tehran
Asia/Thimphu
Asia/Tokyo
Asia/Tomsk
Asia/Ulaanbaatar
Asia/Urumqi
Asia/Ust-Nera
Asia/Vladivostok
Asia/Yakutsk
Asia/Yangon
Asia/Yekaterinburg
Asia/Yerevan
Atlantic/Azores
Atlantic/Bermuda
Atlantic/Canary
Atlantic/Cape_Verde
Atlantic/Faroe
Atlantic/Madeira
Atlantic/Reykjavik
Atlantic/South_Georgia
Atlantic/Stanley
Australia/Adelaide
Australia/Brisbane
Australia/Broken_Hill
Australia/Darwin
Australia/Eucla
Australia/Hobart
Australia/Lindeman
Australia/Lord_Howe
Australia/Melbourne
Australia/Perth
Australia/Sydney
CET
CST6CDT
EET
EST
EST5EDT
Etc/GMT
Etc/GMT+1
Etc/GMT+10
Etc/GMT+11
Etc/GMT+12
Etc/GMT+2
Etc/GMT+3
Etc/GMT+4
Etc/GMT+5
Etc/GMT+6
Etc/GMT+7
Etc/GMT+8
Etc/GMT+9
Etc/GMT-1
Etc/GMT-10
Etc/GMT-11
Etc/GMT-12
Etc/GMT-13
Etc/GMT-14
Etc/GMT-2
Etc/GMT-3
Etc/GMT-4
Etc/GMT-5
Etc/GMT-6
Etc/GMT-7
Etc/GMT-8
Etc/GMT-9
Etc/UTC
Europe/Amsterdam
Europe/Andorra
Europe/Astrakhan
Europe/Athens
Europe/Belgrade
Europe/Berlin
Europe/Brussels
Europe/Bucharest
Europe/Budapest
Europe/Chisinau
Europe/Copenhagen
Europe/Dublin
Europe/Gibraltar
Europe/Helsinki
Europe/Istanbul
Europe/Kaliningrad
Europe/Kiev
Europe/Kirov
Europe/Lisbon
Europe/London
Europe/Luxembourg
Europe/Madrid
Europe/Malta
Europe/Minsk
Europe/Monaco
Europe/Moscow
Europe/Oslo
Europe/Paris
Europe/Prague
Europe/Riga
Europe/Rome
Europe/Samara
Europe/Saratov
Europe/Simferopol
Europe/Sofia
Europe/Stockholm
Europe/Tallinn
Europe/Tirane
Europe/Ulyanovsk
Europe/Uzhgorod
Europe/Vienna
Europe/Vilnius
Europe/Volgograd
Europe/Warsaw
Europe/Zaporozhye
Europe/Zurich
HST
Indian/Chagos
Indian/Christmas
Indian/Cocos
Indian/Kerguelen
Indian/Mahe
Indian/Maldives
Indian/Mauritius
Indian/Reunion
MET
MST
MST7MDT
PST8PDT
Pacific/Apia
Pacific/Auckland
Pacific/Bougainville
Pacific/Chatham
Pacific/Chuuk
Pacific/Easter
Pacific/Efate
Pacific/Enderbury
Pacific/Fakaofo
Pacific/Fiji
Pacific/Funafuti
Pacific/Galapagos
Pacific/Gambier
Pacific/Guadalcanal
Pacific/Guam
Pacific/Honolulu
Pacific/Kiritimati
Pacific/Kosrae
Pacific/Kwajalein
Pacific/Majuro
Pacific/Marquesas
Pacific/Nauru
Pacific/Niue
Pacific/Norfolk
Pacific/Noumea
Pacific/Pago_Pago
Pacific/Palau
Pacific/Pitcairn
Pacific/Pohnpei
Pacific/Port_Moresby
Pacific/Rarotonga
Pacific/Tahiti
Pacific/Tarawa
Pacific/Tongatapu
Pacific/Wake
Pacific/Wallis
I think offset should be also substring 1st character to deal with the negative timezone offset
String offset = data['utc_offset'].substring(0, 3);
Flutter is life.
You don't need to add the offset as the API gives the datetime with the offset pre added
i don't understand why you are using add method to have the datetime in London when this date time is the value of the key "utc datetime"?
To show posibility. Not everyone live in London
@@adamcierniak3902 Since the api already returned time in the requested timezone, he'd have been better off directly printing it here. Since he later uses intl library, he could've used DateFormat.parse to get the user friendly version.
However, if the intent was to demo dart's DateTime - he should've used utc_datetime from the JSON response along with utc_offset for clarity. Also, since there are negative and positive time zone offsets and not all are aligned to an hour either - the parsing to add was insufficient. A note to the user there about the deficiency should've been there. DateTime is hard in general.
It's not UTC all year round because of daylight saving
I believe he was supposed to use the 'utc_datetime' not the 'datetime', then add the offset to it.
The offset should be String offset = data['utc_offset'].substring(0,3); rather than (1,3) to account for timezones that have a negative offset.
Gracias, me funcionó de la manera que mencionas; Estoy usando una zona horaria que tiene ""utc_offset": "-03:00""
Thank You !
Thank you so much for your effort
Hi Shaun,
Please update the video title, its #27 video, and title says #7
and thanks again for such an awesome content
Thanks, sorted :)
4:07
Fascinating advise, actually
just amazing explaination....
Any fix on how to fix this error E/flutter ( 6393): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: SocketException: OS Error: Connection timed out, errno = 110, address = jsonplaceholder.cypress.io, port = 42245
I get it after I try to access the JSON placeholder text. 10 percent of the time it works but then after I reset the error pops back up again
Flutter evolved so much, I think if the they will make a stable version for the web part, it will become a standard.
Also waiting for Flutter for PC, Mac & Linux
@@vigneshs2886 yep, but if it will be for Web, we can wrap it into electron
i don't if this is the best practice for programming or not cause i'm still new to programming in general. but for negative offset i got this to work for me.
// create DateTime object
DateTime now = DateTime.parse(datetime);
print(data['utc_offset'].substring(0,1));
data['utc_offset'].substring(0,1) == '+' ? now = now.add(Duration(hours:int.parse(offset))) :now = now.subtract(Duration(hours:int.parse(offset)));
i dont think you really need to use that ternary operation cause we are already using a substring...instead you may use now.subtract()
bro the world time api link is not in the description box
Amaaazing maaaan thank you sooo much
This is awesome
I know i'm probably just one more random comment here, but I, such as hundreds of people that were following the incredible tutorial that this has been, have not been able to proceed with it. as we're getting errors related to the API. I, myself, was not able to do anything past 4:10.
We would reaaly apreciate ur help, Sir, if possible.
I think it's better to use Current Local Date directly.
Dart DateTime objects don't carry timezone information, toLocal() always returns the date/time converted to the environment's local time. It'll use the UTC offset in the string when parsing to create a DateTime object where isUtc = true, i.e. it adds/subtracts the offset to the time then discards that information. api.dartlang.org/stable/2.6.0/dart-core/DateTime/parse.html. The "timezone" or "time_machine" packages might be helpful, or for this specific case, you could just chop off the offset before parsing to get the intended date/time representation.
its an incredible one there, but i can't find the link to the world time api site in the description box
Can you please explain me the point on why you add now twice to get the updated time?
Will you Master make a tutorial about executing tests in Flutter?
thank you
E/flutter (29833): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: SocketException: Failed host lookup: 'worldtimeapi.org' (OS Error: No address associated with hostname, errno = 7)
E/flutter (29833):
I'm facing this error I'm not understanding what it is can anyone let me know please
you have to have active internet connection on your phone/emulator
Hartley thanks....@The Net Ninja
The request takes more than 1.5 minutes to show a response , am using an Android studio emulator, followed your guide step by step. any idea?
please for the link to the api
@8:52 we make a request and API gives us time as 16:53:48
@9:21 we fix the mistake and API gives us time as 17:54:42
in video time, it is 29 seconds, in real time it is 54 seconds :d
either api is broken or a seamless edit :d
Hey, after parse the date always show me utc date, but not from this place. i have everything the same, what can go wrong?
Bro, do a video on date and time picker🙏
Am following all your tutorials and its amazingly great...🔥🔥,You are a great teacher.....
But it hurts when the worldtime api doesn't work anymore....
Any alternatives?🥺
Bruh, Ive been strugling for 2 hours, but i finally found another site with world time. If you want you could try, lemme know then.
app.abstractapi.com/
You can still use it, just type the host in with "https" instead of "http" so esentially: worldtimeapi.org/api/timezone/...
@@rcexpfpv481 Thank you for this!
@@rcexpfpv481 Thanks. Was stuck on this one for a while
There is this one mistake, that i found out, if we do not consider the + and - sign of utc-offset then it will always be + as we are adding the offset which will always give wrong answers to -ve utc timezones. You can google the current time like chichago current time and compare it with your result. There will be difference in it.
And what should I do when the utc_offset is negative? I've just changed the .substring(1,3) to .substring(0,3) but I want to know if it has another way. Thanks for the videos ♥
Check if the first character of the offset is a '+' or a '-' with an if statement. If it's a '+', call the add method, else call the subtract method.
I did not see a "subtract" method in the Dart docs. In my conditional statement I inserted "-" before "int.parse(offset)", and it worked. However, I think Raphael's approach of using a wider substring is much cleaner. Thanks for the insight!
I used String offset = data['utc_offset'].substring(0, 3); and it worked
One problem that I am discovering is that , we are only changing the offset hours ,and not the minutes.
I appreciate your work and labor, but i have a problem with the data from this api or the api from the last video. no data came to the screen, only lines of did i touched the screen or not....
Now start game development, and teaching us🙏🤗🤗🤗
my time zone is +5:30 , so how do i add that to datetime?, i'm getting an error when adding 5:30 but there is no error when adding just 05.
do you get a solution for this?
The course haS been great but I am getting this error when requesting the API:
Exception has occurred.
ClientException (Connection closed before full header was received)
The time API is flaky. Hit refresh :-)
The worldtimeapi is down currently. What a bummer
I also faced the same issue....
great💜💙
This tutorial series was great, but I think we need an updated version of this. I am incredible confused now that the API website is completely different.
Me too, please can you point me to where I can fine a free world time API, I've scoured the internet and I couldn't find any
@@billikpe2718 Did you figure it out man?
@@jamescoughlin6357 nope, I put a pause on that project
can still use the same, but I have another problem It will take some number of times to response, after I tried the third time only I recieved the response, but then when I hot reload again, it couldnt zzz....sometimes due to timeout and connection closed, so when u try to get the response when u request the worldtime api, it doesnt reach you and throws an error, I think just continue this tutorial playlist until exception handling
ruclips.net/video/AqsmaT1U6sQ/видео.html offset is +01 but you removed + and only took 01 What if it is -04, 04 will be added to original time which is wrong, is it?
What is the extension you use to view JSON data in your browser? Thanks for the great tutorial!
Not the exact same extension, but if you google "Chrome JSON Viewer" the first one that pops up is "JSON Viewer" and it's what I use. It has some pretty cool display configurations.
if you use mozilla firefox, you don't need extension :)
Sir, The course project is out of date. Get error but I learn so many things.Thank you.
I really liked your video, they are very helpful, I want to ask if you use a son formatted extinction that allows you to display json in your browser like in the video ?
just use mozilla firefox
@@ranjanpanda2586 I used a google chrome extension, thank you
@@DoctorCode9 Saw your channel though. Loved it !!
Do you make your source code public for the videos you make ??
@@ranjanpanda2586 Thank you for your feedback, yeah I share all my source code in my personal blog you will find it in my videos description and Soon I will release them into my github
I get this error when I am using api, "Insecure HTTP is not allowed by platform" because its not a https endpoint. Is there an alternative?
Bruh, Ive been strugling for 2 hours, but i finally found another site with world time. If you want you could try, lemme know then.
app.abstractapi.com/
@@mac3k282 Thanks man, I moved on doing other tutorials. Thank you though.
At 8:52 he say's the "now" object is "non-destructive." What does that mean? I'm from Java but I haven't come across that term yet in Java.
He actually kind of forgets there are offsets like -01:30, denoting negative offset having hours as 1 and minutes as 30.
A quick fix to this, although I'm sure there are better methods around, is:
String datetime = time['datetime'];
List offset =
time['utc_offset'].split(':').map((e) => int.parse(e)).toList();
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: offset[0], minutes: offset[1]));
Thanks Bro ... short and concise...this helped....Indian offset is +5:30
why do we need to add the utc offset?....coz already the local time is given as datetime
Should I need a stable internet to do this?
You can't just remove first symbol from the offset. Offset can be negative and then you need this minus. Moreover, why converting it to an integer if it's clearly of type Time.
Also, what is "non destructive"? I though types like this are called "immutable."