How to get date and time from the internet in Flutter

Are you building a Flutter application and need to display the current date and time based on the user’s location or a specific timezone? Rather than relying on the user’s device settings, you can fetch the precise date and time from the internet using the WorldTimeAPI. In this blog post, we will take a look at How to get date and time from the internet in Flutter

Implementing the DateTimeService Class

To begin, let’s create a Flutter class called DateTimeService that will handle the communication with the WorldTimeAPI and retrieve the current date and time. Open your Flutter project and create a new file called date_time_service.dart. Add the following code to the file:

				
					import 'dart:convert';
import 'package:http/http.dart' as http;

class DateTimeService {
  static Future<DateTime> getCurrentDateTime() async {
    final url = Uri.parse('http://worldtimeapi.org/api/timezone/Etc/UTC');
    final response = await http.get(url);

    if (response.statusCode == 200) {
      final jsonResponse = jsonDecode(response.body);
      final datetime = DateTime.parse(jsonResponse['datetime']);
      return datetime;
    } else {
      throw Exception('Failed to fetch date and time');
    }
  }
}
				
			

In this code snippet, we import the necessary libraries: dart:convert for JSON decoding and http for making HTTP requests. The DateTimeService class provides a single static method called getCurrentDateTime() that returns a Future<DateTime>.

Inside the getCurrentDateTime() method, we define the URL of the WorldTimeAPI endpoint for the UTC timezone. We then use the http package to send an HTTP GET request to the URL and await the response. If the response status code is 200 (indicating a successful request), we parse the JSON response using jsonDecode() and extract the 'datetime' value. This value is then converted into a DateTime object and returned. If the response status code is not 200, we throw an exception indicating that the date and time fetch failed.

Using the DateTimeService in Your Flutter Application

Now that we have our DateTimeService class ready, we can utilize it in our Flutter application to fetch the current date and time from the internet. You can call the getCurrentDateTime() method wherever you need to display the date and time information in your app. Remember to import the date_time_service.dart file into your desired Flutter widget.

Here’s an example of how you can use the DateTimeService class in your Flutter application:

				
					import 'package:flutter/material.dart';
import 'date_time_service.dart';

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Date and Time Example'),
      ),
      body: Center(
        child: FutureBuilder<DateTime>(
          future: DateTimeService.getCurrentDateTime(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              final dateTime = snapshot.data!;
              return Text(
                'Current Date and Time: $dateTime',
                style: TextStyle(fontSize: 24),
              );
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              return CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}

				
			

In this example, we have a simple MyHomePage widget that displays the current date and time obtained from the DateTimeService. We use a FutureBuilder widget to handle the asynchronous nature of the getCurrentDateTime() method. When the future resolves, we check if we have data or an error in the snapshot. If we have data, we extract the DateTime object and display it using a Text widget. If there’s an error, we display the error message, and if the future is still loading, we show a CircularProgressIndicator.

Happy coding!


Read our other blogs: Click Here 

, ,