flutterdartdatetimecalendardatetimepicker

How to show only date in Date time class?


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 the result of my code:

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 ! 🙏


Solution

  • You have two solutions here. The first one (the easier) is to turn the DateTime object into a string, then split it and get the first part like this:

    final DateTime now = DateTime.now();
    now.toString().split(' ')[0]
    

    And this will do; however, if you want more control, I suggest you read this answer.