From 4ab7f4ac02d79d7174b3742fece061e97ebb84ab Mon Sep 17 00:00:00 2001 From: akashpunagin Date: Sun, 19 Jan 2020 21:01:36 +0530 Subject: [PATCH] Added offsetMinutes and managed negative offset --- world_time_app/lib/services/world_time.dart | 41 ++++++++++++--------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/world_time_app/lib/services/world_time.dart b/world_time_app/lib/services/world_time.dart index fd1ec41..fb4ad9e 100644 --- a/world_time_app/lib/services/world_time.dart +++ b/world_time_app/lib/services/world_time.dart @@ -2,40 +2,47 @@ import 'package:http/http.dart'; import 'dart:convert'; import 'package:intl/intl.dart'; -class WorldTime { +class WorldTime{ + String location; // location name for the UI + String time; // time in that location + String flag; // url to asset flag icon + String url; // location url for API endpoint + bool isDayTime; // true or false / day or night - String location; // location name for UI - String time; // the time in that location - String flag; // url to an asset flag icon - String url; // location url for api endpoint - bool isDaytime; // true or false if daytime or not - - WorldTime({ this.location, this.flag, this.url }); + WorldTime({ this.location, this.flag, this.url}); Future getTime() async { - try{ - // make the request + try { + //make the request Response response = await get('http://worldtimeapi.org/api/timezone/$url'); Map data = jsonDecode(response.body); + print(data); + - // get properties from json + //get properties from data String datetime = data['datetime']; - String offset = data['utc_offset'].substring(1,3); + int offsetHours = int.parse(data['utc_offset'].substring(1,3)); + int offsetMinutes = int.parse(data['utc_offset'].substring(4,6)); + + if (data['utc_offset'].substring(0, 1) == "-") { + offsetHours = -offsetHours; + offsetMinutes = -offsetMinutes; + } // create DateTime object DateTime now = DateTime.parse(datetime); - now = now.add(Duration(hours: int.parse(offset))); + now = now.add(Duration(hours: offsetHours, minutes: offsetMinutes)); - // set the time property - isDaytime = now.hour > 6 && now.hour < 20 ? true : false; + // set time property + isDayTime = now.hour > 6 && now.hour < 19 ? true : false; time = DateFormat.jm().format(now); } catch (e) { - print(e); - time = 'could not get time'; + time = 'Could not get the requested time, sorry!'; } + } } \ No newline at end of file