refactored code to encapsulate date formatting
This commit is contained in:
@@ -1,11 +1,13 @@
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'dart:convert';
|
||||
import 'package:timezone/timezone.dart' as tz;
|
||||
|
||||
import '../model/flood_station.dart';
|
||||
import '../model/reading.dart';
|
||||
import 'date_utility.dart';
|
||||
|
||||
class Api {
|
||||
Api._();
|
||||
|
||||
static const String _rootUrl =
|
||||
'https://environment.data.gov.uk/flood-monitoring';
|
||||
|
||||
@@ -56,7 +58,8 @@ class Api {
|
||||
static Future<List<Reading>> fetchReadingsFromStation(
|
||||
String stationId) async {
|
||||
List<Reading> readings = [];
|
||||
final dateTime = _getCurrentUKTime().subtract(Duration(days: 1)).toUtc();
|
||||
final dateTime =
|
||||
DateUtility.currentUKTimeUtc.subtract(Duration(days: 1)).toUtc();
|
||||
final url =
|
||||
'$_rootUrl/id/stations/$stationId/readings?since=${dateTime.toIso8601String()}&_sorted';
|
||||
final response = await http.get(Uri.parse(url));
|
||||
@@ -68,9 +71,4 @@ class Api {
|
||||
}
|
||||
return readings.reversed.toList();
|
||||
}
|
||||
|
||||
static DateTime _getCurrentUKTime() {
|
||||
final london = tz.getLocation('Europe/London');
|
||||
return tz.TZDateTime.now(london);
|
||||
}
|
||||
}
|
||||
|
||||
36
lib/services/date_utility.dart
Normal file
36
lib/services/date_utility.dart
Normal file
@@ -0,0 +1,36 @@
|
||||
import 'package:timezone/timezone.dart' as tz;
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
|
||||
class DateUtility {
|
||||
static final intl.DateFormat _hmFormat = intl.DateFormat('Hm');
|
||||
static final intl.DateFormat _ymdhmFormat = intl.DateFormat('yyyy-MM-dd H:m');
|
||||
static final intl.DateFormat _ymdFormat = intl.DateFormat('yyyy-MM-dd');
|
||||
|
||||
// private default contructor so class can't be instanciated
|
||||
DateUtility._();
|
||||
|
||||
static DateTime get currentUKTimeUtc {
|
||||
final london = tz.getLocation('Europe/London');
|
||||
return tz.TZDateTime.now(london).toUtc();
|
||||
}
|
||||
|
||||
/// Formats a date in minutesSinceEpoch to a formatted String of HH:mm
|
||||
static String formatMinutesToHm(double value) {
|
||||
return _hmFormat.format(
|
||||
DateTime.fromMillisecondsSinceEpoch((value * 1000 * 60).toInt()));
|
||||
}
|
||||
|
||||
static String formatDateToHm(DateTime date) {
|
||||
return _hmFormat.format(date);
|
||||
}
|
||||
|
||||
/// Formats a date to yyyy-MM-dd H:m
|
||||
static String formatDateToYmdhm(DateTime date) {
|
||||
return _ymdhmFormat.format(date);
|
||||
}
|
||||
|
||||
/// Formats a date to yyyy-MM-dd
|
||||
static String formatDateToYmd(DateTime date) {
|
||||
return _ymdFormat.format(date);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user