Merge pull request #891 from wger-project/fix/timezone-problems

Better handling of time zones
This commit is contained in:
Roland Geider
2025-08-28 22:42:21 +02:00
committed by GitHub
30 changed files with 170 additions and 106 deletions

40
lib/helpers/date.dart Normal file
View File

@@ -0,0 +1,40 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wger Workout Manager is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// Returns a timezone aware DateTime object from a date and time string.
DateTime getDateTimeFromDateAndTime(String date, String time) {
return DateTime.parse('$date $time');
}
/// Returns a list of [DateTime] objects from [first] to [last], inclusive.
List<DateTime> daysInRange(DateTime first, DateTime last) {
final dayCount = last.difference(first).inDays + 1;
return List.generate(
dayCount,
(index) => DateTime.utc(first.year, first.month, first.day + index),
);
}
extension DateTimeExtension on DateTime {
bool isSameDayAs(DateTime other) {
final thisDay = DateTime(year, month, day);
final otherDay = DateTime(other.year, other.month, other.day);
return thisDay.isAtSameMomentAs(otherDay);
}
}

View File

@@ -53,6 +53,15 @@ String? dateToYYYYMMDD(DateTime? dateTime) {
return DateFormat('yyyy-MM-dd').format(dateTime);
}
/// Convert a date to UTC and then to an ISO8601 string.
///
/// This makes sure that the serialized data has correct timezone information.
/// Otherwise the django backend will possibly treat the date as local time,
/// which will not be correct in most cases.
String dateToUtcIso8601(DateTime dateTime) {
return dateTime.toUtc().toIso8601String();
}
/*
* Converts a time to a date object.
* Needed e.g. when the wger api only sends a time but no date information.

View File

@@ -63,38 +63,6 @@ String repText(
return out.join(' ');
}
/// Returns a list of [DateTime] objects from [first] to [last], inclusive.
List<DateTime> daysInRange(DateTime first, DateTime last) {
final dayCount = last.difference(first).inDays + 1;
return List.generate(
dayCount,
(index) => DateTime.utc(first.year, first.month, first.day + index),
);
}
extension TimeOfDayExtension on TimeOfDay {
bool isAfter(TimeOfDay other) {
return toMinutes() > other.toMinutes();
}
bool isBefore(TimeOfDay other) {
return toMinutes() < other.toMinutes();
}
int toMinutes() {
return (hour * 60) + minute;
}
}
extension DateTimeExtension on DateTime {
bool isSameDayAs(DateTime other) {
final thisDay = DateTime(year, month, day);
final otherDay = DateTime(other.year, other.month, other.day);
return thisDay.isAtSameMomentAs(otherDay);
}
}
void launchURL(String url, BuildContext context) async {
final scaffoldMessenger = ScaffoldMessenger.of(context);
final launched = await launchUrl(Uri.parse(url));

View File

@@ -36,7 +36,7 @@ class Log {
@JsonKey(required: true, name: 'plan')
int planId;
@JsonKey(required: true)
@JsonKey(required: true, toJson: dateToUtcIso8601)
late DateTime datetime;
String? comment;

View File

@@ -27,7 +27,7 @@ Map<String, dynamic> _$LogToJson(Log instance) => <String, dynamic>{
'id': instance.id,
'meal': instance.mealId,
'plan': instance.planId,
'datetime': instance.datetime.toIso8601String(),
'datetime': dateToUtcIso8601(instance.datetime),
'comment': instance.comment,
'ingredient': instance.ingredientId,
'weight_unit': instance.weightUnitId,

View File

@@ -19,8 +19,8 @@
import 'package:flutter/material.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/models/nutrition/log.dart';
import 'package:wger/models/nutrition/meal_item.dart';
import 'package:wger/models/nutrition/nutritional_values.dart';

View File

@@ -38,7 +38,7 @@ class NutritionalPlan {
@JsonKey(required: true)
late String description;
@JsonKey(required: true, name: 'creation_date', toJson: dateToYYYYMMDD)
@JsonKey(required: true, name: 'creation_date', toJson: dateToUtcIso8601)
late DateTime creationDate;
@JsonKey(required: true, name: 'only_logging')

View File

@@ -37,7 +37,7 @@ NutritionalPlan _$NutritionalPlanFromJson(Map<String, dynamic> json) {
Map<String, dynamic> _$NutritionalPlanToJson(NutritionalPlan instance) => <String, dynamic>{
'id': instance.id,
'description': instance.description,
'creation_date': dateToYYYYMMDD(instance.creationDate),
'creation_date': dateToUtcIso8601(instance.creationDate),
'only_logging': instance.onlyLogging,
'goal_energy': instance.goalEnergy,
'goal_protein': instance.goalProtein,

View File

@@ -80,7 +80,7 @@ class Log {
@JsonKey(includeFromJson: false, includeToJson: false)
late WeightUnit? weightUnitObj;
@JsonKey(required: true, toJson: dateToYYYYMMDD)
@JsonKey(required: true, toJson: dateToUtcIso8601)
late DateTime date;
Log({

View File

@@ -58,5 +58,5 @@ Map<String, dynamic> _$LogToJson(Log instance) => <String, dynamic>{
'weight': numToString(instance.weight),
'weight_target': numToString(instance.weightTarget),
'weight_unit': instance.weightUnitId,
'date': dateToYYYYMMDD(instance.date),
'date': dateToUtcIso8601(instance.date),
};

View File

@@ -17,8 +17,8 @@
*/
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/models/workouts/day.dart';
import 'package:wger/models/workouts/day_data.dart';
import 'package:wger/models/workouts/log.dart';
@@ -42,7 +42,7 @@ class Routine {
@JsonKey(required: true, includeToJson: false)
int? id;
@JsonKey(required: true)
@JsonKey(required: true, toJson: dateToUtcIso8601)
late DateTime created;
@JsonKey(required: true, name: 'name')

View File

@@ -31,7 +31,7 @@ Routine _$RoutineFromJson(Map<String, dynamic> json) {
}
Map<String, dynamic> _$RoutineToJson(Routine instance) => <String, dynamic>{
'created': instance.created.toIso8601String(),
'created': dateToUtcIso8601(instance.created),
'name': instance.name,
'description': instance.description,
'fit_in_week': instance.fitInWeek,

View File

@@ -421,7 +421,7 @@ class NutritionPlansProvider with ChangeNotifier {
]) async {
final plan = findById(planId);
mealItem.ingredient = await fetchIngredient(mealItem.ingredientId);
final Log log = Log.fromMealItem(mealItem, plan.id!, null, dateTime);
final log = Log.fromMealItem(mealItem, plan.id!, null, dateTime);
final data = await baseProvider.post(
log.toJson(),

View File

@@ -18,6 +18,7 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/nutrition/meal.dart';
@@ -70,8 +71,10 @@ class _LogMealScreenState extends State<LogMealScreen> {
.toList(),
);
final i18n = AppLocalizations.of(context);
return Scaffold(
appBar: AppBar(title: Text(AppLocalizations.of(context).logMeal)),
appBar: AppBar(title: Text(i18n.logMeal)),
body: Consumer<NutritionPlansProvider>(
builder: (context, nutritionProvider, child) => SingleChildScrollView(
child: Padding(
@@ -83,7 +86,7 @@ class _LogMealScreenState extends State<LogMealScreen> {
style: Theme.of(context).textTheme.headlineSmall,
),
if (meal.mealItems.isEmpty)
ListTile(title: Text(AppLocalizations.of(context).noIngredientsDefined))
ListTile(title: Text(i18n.noIngredientsDefined))
else
Column(
children: [
@@ -113,7 +116,7 @@ class _LogMealScreenState extends State<LogMealScreen> {
child: TextFormField(
key: const ValueKey('field-date'),
readOnly: true,
decoration: InputDecoration(labelText: AppLocalizations.of(context).date),
decoration: InputDecoration(labelText: i18n.date),
enableInteractiveSelection: false,
controller: _dateController,
onTap: () async {
@@ -138,7 +141,7 @@ class _LogMealScreenState extends State<LogMealScreen> {
child: TextFormField(
key: const ValueKey('field-time'),
readOnly: true,
decoration: InputDecoration(labelText: AppLocalizations.of(context).time),
decoration: InputDecoration(labelText: i18n.time),
controller: _timeController,
onTap: () async {
// Open time picker
@@ -165,28 +168,32 @@ class _LogMealScreenState extends State<LogMealScreen> {
children: [
if (meal.mealItems.isNotEmpty)
TextButton(
child: const Text('Log'),
child: Text(i18n.save),
onPressed: () async {
final loggedTime = getDateTimeFromDateAndTime(
_dateController.text,
_timeController.text,
);
await Provider.of<NutritionPlansProvider>(
context,
listen: false,
).logMealToDiary(
meal,
DateTime.parse('${_dateController.text} ${_timeController.text}'),
);
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
// ignore: use_build_context_synchronously
AppLocalizations.of(context).mealLogged,
textAlign: TextAlign.center,
).logMealToDiary(meal, loggedTime);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
i18n.mealLogged,
textAlign: TextAlign.center,
),
),
),
);
Navigator.of(context).pop();
if (args.popTwice) {
);
Navigator.of(context).pop();
if (args.popTwice) {
Navigator.of(context).pop();
}
}
},
),

View File

@@ -60,7 +60,7 @@ class NutritionalPlanScreen extends StatelessWidget {
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).logIngredient,
IngredientLogForm(nutritionalPlan),
getIngredientLogForm(nutritionalPlan),
hasListView: true,
),
);

View File

@@ -21,8 +21,8 @@ import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/providers/body_weight.dart';
import 'package:wger/providers/measurement.dart';

View File

@@ -108,7 +108,7 @@ class _DashboardNutritionWidgetState extends State<DashboardNutritionWidget> {
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).logIngredient,
IngredientLogForm(_plan!),
getIngredientLogForm(_plan!),
hasListView: true,
),
);

View File

@@ -19,7 +19,7 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/workouts/day_data.dart';
import 'package:wger/models/workouts/routine.dart';

View File

@@ -20,6 +20,7 @@ import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/nutrition/ingredient.dart';
@@ -114,7 +115,7 @@ class MealForm extends StatelessWidget {
}
}
Widget MealItemForm(
Widget getMealItemForm(
Meal meal,
List<MealItem> recent, [
String? barcode,
@@ -133,7 +134,7 @@ Widget MealItemForm(
);
}
Widget IngredientLogForm(NutritionalPlan plan) {
Widget getIngredientLogForm(NutritionalPlan plan) {
return IngredientForm(
recent: plan.dedupDiaryEntries,
onSave: (BuildContext context, MealItem mealItem, DateTime? dt) {
@@ -397,16 +398,11 @@ class IngredientFormState extends State<IngredientForm> {
_form.currentState!.save();
_mealItem.ingredientId = int.parse(_ingredientIdController.text);
var date = DateTime.parse(_dateController.text);
final tod = stringToTime(_timeController.text);
date = DateTime(
date.year,
date.month,
date.day,
tod.hour,
tod.minute,
final loggedDate = getDateTimeFromDateAndTime(
_dateController.text,
_timeController.text,
);
widget.onSave(context, _mealItem, date);
widget.onSave(context, _mealItem, loggedDate);
Navigator.of(context).pop();
},

View File

@@ -116,7 +116,7 @@ class _MealWidgetState extends State<MealWidget> {
FormScreen.routeName,
arguments: FormScreenArguments(
AppLocalizations.of(context).addIngredient,
MealItemForm(widget._meal, widget._recentMealItems),
getMealItemForm(widget._meal, widget._recentMealItems),
hasListView: true,
),
);

View File

@@ -17,7 +17,7 @@
*/
import 'package:flutter/material.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/workouts/day_data.dart';

View File

@@ -227,15 +227,18 @@ class _LogPageState extends ConsumerState<LogPage> {
context,
listen: false,
).addLog(widget._log);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
duration: const Duration(seconds: 2), // default is 4
content: Text(
AppLocalizations.of(context).successfullySaved,
textAlign: TextAlign.center,
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
duration: const Duration(seconds: 2), // default is 4
content: Text(
AppLocalizations.of(context).successfullySaved,
textAlign: TextAlign.center,
),
),
),
);
);
}
widget._controller.nextPage(
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,

View File

@@ -18,7 +18,7 @@
import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/workouts/routine.dart';

View File

@@ -19,6 +19,7 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:wger/helpers/colors.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/helpers/errors.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/l10n/generated/app_localizations.dart';

View File

@@ -21,8 +21,8 @@ import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/models/body_weight/weight_entry.dart';
import 'package:wger/providers/body_weight.dart';

View File

@@ -8,7 +8,7 @@ import 'package:shared_preferences_platform_interface/in_memory_shared_preferenc
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:wger/database/exercises/exercise_database.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/helpers/date.dart';
import 'package:wger/helpers/shared_preferences.dart';
import 'package:wger/models/exercises/exercise_api.dart';
import 'package:wger/models/exercises/muscle.dart';

View File

@@ -1,3 +1,21 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wger Workout Manager is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/helpers/colors.dart';

View File

@@ -1,6 +1,6 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2020, 2021 wger Team
* Copyright (C) wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
@@ -16,21 +16,16 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/helpers/date.dart';
void main() {
test('Test the TimeOfDayExtension', () {
const time1 = TimeOfDay(hour: 00, minute: 00);
const time2 = TimeOfDay(hour: 23, minute: 59);
expect(time2.toMinutes(), 23 * 60 + 59);
expect(time1.isAfter(time2), false);
expect(time1.isBefore(time2), true);
expect(time2.isAfter(time1), true);
expect(time2.isBefore(time1), false);
expect(time1.isAfter(time1), false);
expect(time2.isBefore(time2), false);
group('getDateTimeFromDateAndTime', () {
test('should correctly generate a DateTime', () {
expect(
getDateTimeFromDateAndTime('2025-05-16', '17:02'),
DateTime(2025, 5, 16, 17, 2),
);
});
});
}

View File

@@ -1,3 +1,21 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wger Workout Manager is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/helpers/json.dart';
@@ -39,6 +57,15 @@ void main() {
});
});
group('dateToIsoWithTimezone', () {
test('should format DateTime to a string with timezone', () {
expect(
dateToUtcIso8601(DateTime.parse('2025-05-16T18:15:00+02:00')),
'2025-05-16T16:15:00.000Z',
);
});
});
group('stringToTime', () {
test('should default to 00:00 for null input', () {
expect(stringToTime(null), const TimeOfDay(hour: 0, minute: 0));

View File

@@ -101,7 +101,7 @@ void main() {
home: Scaffold(
body: Scrollable(
viewportBuilder: (BuildContext context, ViewportOffset position) =>
MealItemForm(meal, const [], code, test),
getMealItemForm(meal, const [], code, test),
),
),
routes: {