Hi,
I like to make things simple and effective. I needed to convert UTC to local time for my own project. I want to share my solution with you.
If we want to develop an international app, we have to convert DateTime to the user’s local time. Because most international apps store DateTime as UTS in their database. As mobile application developers, we should convert this DateTime data to the user’s local time zone. We can do it with the “data.toLocal()” method. But if we send data to the server, we have to convert DateTime values to UTC. Every time, we have to convert, and this is not the best solution.
What about the JSON converter?
Most of the time, we use JSON serialization in our apps. For that, we write models and toJSON and fromJSON methods. We can convert our DateTime fields using these methods. What will we do? When we use the toJSON method, we will convert DateTime fields to UTC format, and when we use the fromJSON method, we will convert DateTime fields to the local format. We can do this with JSONConverter.
How can we develop our converter?
We can create our converters by implementing the JsonConverter. I created a converter whose name is UTCDateTimeConverter. It is simple to use. We will add UTCDateTimeConverter as an attribute to our models. And run build_runner. Thats all.
Step 1: Create a converter class
import 'package:json_annotation/json_annotation.dart';
class UTCDateTimeConverter implements JsonConverter<DateTime, String> {
const UTCDateTimeConverter();
@override
DateTime fromJson(String dateTime) {
return DateTime.parse(dateTime).toLocal();
}
@override
String toJson(DateTime dateTime) {
return dateTime.toUtc().toString();
}
}
Step 2: Add the converter to the model
@JsonSerializable()
@UTCDateTimeConverter()
class User {
String name;
DateTime lastLoginDate;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
Now, when we use our models, the DateTime fields will be in local format. And when we send our models to the server, the DateTime fields will be converted into UTC format. We don’t need to convert our DateTime fields manually anymore.
Thank you.