我有一个自定义模型类Timestamp
,其中我有一个构造函数,它接受对象DateTime
并实例化Timestamp
数据。
如何将此类转换为使用freezed
?
class Timestamp {
const Timestamp({
required date,
required time,
}) {
RegExp dateRegExp = RegExp(
r'^\d{2}-\d{2}-\d{4}$',
);
assert(dateRegExp.hasMatch(date));
RegExp timeRegExp = RegExp(
r'^\d{2}:\d{2}:\d{2}$',
);
assert(dateRegExp.hasMatch(date));
assert(timeRegExp.hasMatch(time));
_date = date;
_time = time;
}
Timestamp.fromDateTime({
required DateTime dateTime,
}) {
_date = '${dateTime.day.toString().padLeft(2, '0')}'
'-'
'${dateTime.month.toString().padLeft(2, '0')}'
'-'
'${dateTime.year.toString().padLeft(2, '4')}';
_time = '${dateTime.hour.toString().padLeft(2, '0')}'
':'
'${dateTime.minute.toString().padLeft(2, '0')}'
':'
'${dateTime.second.toString().padLeft(2, '0')}';
}
/// Format - 'dd-MM-yyyy'
final String _date = '';
/// Format - 'HH:mm:ss' (24 hour time)
final String _time = '';
String get date => _date;
String get time => _time;
DateTime toDateTime() {
List<String> dateSubStrings = _date.split('-');
List<String> timeSubStrings = _time.split(':');
return DateTime.utc(
int.parse(dateSubStrings[2]),
int.parse(dateSubStrings[1]),
int.parse(dateSubStrings[0]),
int.parse(timeSubStrings[0]),
int.parse(timeSubStrings[1]),
int.parse(timeSubStrings[2]),
);
}
// hashCode, toString, and equality methods
}