i am trying to show a calendar in order to user choose a reservation date by clicking the reserve button . and the reservation day’s date is shown below the button.
i am using DateTime class.
i have two questions :
1- i want to "just" show the date of reservation day . i don’t need exact hours and time and i don’t khow how to do it . i tried with "spilt and a range" but i couldn’t.
2- do you khow what is the usage of that toLocal() method there (Text(‘reservation date : ${selectedtime.toLocal()}’),) in my code? is that necessary there or not?
here is my whole code:
import "package:flutter/material.dart";
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyPage(),
);
}
}
class MyPage extends StatefulWidget {
const MyPage({super.key});
@override
State<MyPage> createState() => _Example();
}
class _Example extends State<MyPage> {
DateTime selectedtime = DateTime.now();
datePicker(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: selectedtime,
firstDate: DateTime(2023),
lastDate: DateTime(2025));
if (picked != null && picked != selectedtime) {
setState(() {
selectedtime = picked;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('HDBOOKS'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: ElevatedButton(
onPressed: () => datePicker(context),
child: const Text('reserve')),
),
const SizedBox(
height: 36,
),
Text('reservation date : ${selectedtime.toLocal()}'),
],
),
);
}
}
here is my code when i wanted to fix the problem with split:
//when i use split i need a range of things to be shown but i don’t khow how to use range in split.
it raises error!
Text(
'reservation date : ${selectedtime.toLocal()}'.split(' ')[0 : 3]),
please help me thank you ! 🙏
2
Answers
You Have Two Solutions Here The First One (The Easiest) is to turn the DateTime Object into a String Then Split it and get The First Part Like This :
And this will do, however if you want more control I suggest you read this answer.
DateFormat
class fromintl
package to format.toLocal()
ensures the local time of the device, also some countries use daylight savings.