Search code examples
androidflutterandroid-studiodatetimedatetimeoffset

Why can't I add offset hours in datetime Flutter project?


I tried to add offset hours to my datetime object now, but it doesn't show the added time that is actual time. It is my flutter project in android studio.

    void getTime() async {
    Response response = await
    get('http://worldtimeapi.org/api/timezone/Asia/Karachi');
    Map data = jsonDecode(response.body);
    String datetime = data['datetime'];
    String offset = data['utc_offset'].substring(1,3);

    print(offset);
    DateTime now = DateTime.parse(datetime);
    now.add(Duration(hours: int.parse('offset')));
    print(now);
    }
    @override
    void initState() {
    super.initState();
    getTime();
    }

This is the result I got: Screenshot of the output


Solution

  • I found the solution. Yayyy!

      void getTime() async {
    
        //Make the request
        Response response = await get('http://worldtimeapi.org/api/timezone/Asia/Karachi');
        Map data = jsonDecode(response.body);
        print(data);
    
    
        //Get properties from data
        String datetime = data['datetime'];
        String offset = data['utc_offset'].substring(1,3);
        //print(datetime);
        print(offset);
    
        //create DateTime Object
        DateTime now = DateTime.parse(datetime);
        now = now.add(Duration(hours: int.parse(offset)));
        print(now);
      }
    
      @override
      void initState() {
    
        super.initState();
        getTime();
      }