How do I change the format of the date? I am using a datepicker to pick a date but I want the date to display as dd/mm/yyyy, here is the code
class DatePicker extends StatefulWidget {
const DatePicker({Key? key}) : super(key: key);
@override
State<DatePicker> createState() => _DatePickerState();
}
class _DatePickerState extends State<DatePicker> {
DateTime selectedDate = DateTime.now();
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2015, 8),
lastDate: DateTime(2101));
if (picked != null && picked != selectedDate) {
setState(() {
selectedDate = picked;
});
}
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
InkWell(
onTap: () => _selectDate(context),
child: Text("${selectedDate.toLocal()}".split(' ')[0])),
SizedBox(
height: 20.0,
),
],
);
}
}
CodePudding user response:
Try using instead of
child: Text("${selectedDate.toLocal()}".split(' ')[0])),
do
child: Text(DateFormat('dd/MM/yyyy').format(selectedDate)),
CodePudding user response:
Please try this
var formattedSelectedDate;
if (picked != null && picked != selectedDate) {
setState(() {
final DateFormat formatter = DateFormat('yyyy-MM-dd');
final String formatted = formatter.format(picked);
print(formatted);
selectedDate = picked;
formattedSelectedDate = formatted;
});
}
Use this "formattedSelectedDate" to display on the UI.
CodePudding user response:
For displaying the date you should use this
Text("${selectedDate.day}/${selectedDate.month}/${selectedDate.year}"),