Building a Flutter app with DateTime Picker - Get DateTime From DateTime String

Last updated Oct 30, 2020

With the Flutter date time picker plugin, we can add Date and Time picker to our Native applications.

In this post, we are going to create a Flutter application with the Date & Time feature.

How to pick date and time in the Flutter application.

 

Start to Create a Simple Flutter Application here

Flutter DateTimePicker

 

The DateTime Picker Constructor 

showDatePicker(
  BuildContext context, {
  bool showTitleActions: true,
  DateTime minTime,
  DateTime maxTime,
  DateChangedCallback onChanged,
  DateChangedCallback onConfirm,
  DateCancelledCallback onCancel,
  locale: LocaleType.en,
  DateTime currentTime,
  DatePickerTheme theme,
})

 

Let's create a Flutter Application with Date Time Picker feature.

Step 1: Create a Flutter application

Step 2: Add dependencies in pubspec.yaml file.

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_datetime_picker:

 

Step 3: Run flutter pub get  command in terminal 

Step 4: Create a file and import Data time picker packages

import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

 

Complete code

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
class DateTimePicker extends StatefulWidget {
  @override
  _DateTimePickerState createState() => _DateTimePickerState();
}

class _DateTimePickerState extends State<DateTimePicker> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String _date = "Not set";
  String _time = "Not set";

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DateTime Picker'),
        backgroundColor: Colors.purpleAccent,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Container(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5.0)),
                elevation: 4.0,
                onPressed: () {
                  DatePicker.showDatePicker(context,
                      theme: DatePickerTheme(
                        containerHeight: 210.0,
                        backgroundColor: Colors.blueGrey,
                        headerColor: Colors.white,
                        cancelStyle: TextStyle(color:Colors.grey),
                        doneStyle: TextStyle(color: Colors.red),
                        itemStyle: TextStyle(color: Colors.white)
                      ),
                      showTitleActions: true,
                      minTime: DateTime(2000, 1, 1),
                      maxTime: DateTime(2020, 10, 30), onConfirm: (date) {
                        print('confirm $date');
                        _date = '${date.year} - ${date.month} - ${date.day}';
                        setState(() {});
                      }, currentTime: DateTime.now(), locale: LocaleType.en);
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 50.0,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Container(
                            child: Row(
                              children: <Widget>[
                                Icon(
                                  Icons.date_range,
                                  size: 18.0,
                                  color: Colors.purple,
                                ),
                                Text(
                                  " $_date",
                                  style: TextStyle(
                                      color: Colors.purpleAccent,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18.0),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                      Text(
                        "  Change",
                        style: TextStyle(
                            color: Colors.purple,
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0),
                      ),
                    ],
                  ),
                ),
                color: Colors.white,
              ),
              SizedBox(
                height: 20.0,
              ),
              RaisedButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5.0)),
                elevation: 4.0,
                onPressed: () {
                  DatePicker.showTimePicker(context,
                      theme: DatePickerTheme(
                        containerHeight: 210.0,
                          backgroundColor: Colors.blueGrey,
                          headerColor: Colors.white,
                          cancelStyle: TextStyle(color:Colors.grey),
                          doneStyle: TextStyle(color: Colors.red),
                          itemStyle: TextStyle(color: Colors.white)
                      ),
                      showTitleActions: true, onConfirm: (time) {
                        print('confirm $time');
                        _time = '${time.hour} : ${time.minute} : ${time.second}';
                        setState(() {});
                      }, currentTime: DateTime.now(), locale: LocaleType.en);
                  setState(() {});
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 50.0,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Container(
                            child: Row(
                              children: <Widget>[
                                Icon(
                                  Icons.access_time,
                                  size: 18.0,
                                  color: Colors.purple,
                                ),
                                Text(
                                  " $_time",
                                  style: TextStyle(
                                      color: Colors.purple,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18.0),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                      Text(
                        "  Change",
                        style: TextStyle(
                            color: Colors.purple,
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0),
                      ),
                    ],
                  ),
                ),
                color: Colors.white,
              )
            ],
          ),
        ),
      ),
    );
  }
}

 

 

 

How to convert DateTime String to DateTime in Flutter?

 

With the DateTime.now() function we will get the Current Date Time in a flutter.

If we have a date and time in string formate to get DataTime Object from this String we can convert DateTimeString to DateTime by 

var parsedDate = DateTime.parse('2020-03-03 00:00:00.000');

 

DateTime.parse method will return DateTime Object from given DateTime String.

 

 

How to get Year, Month, and Day from DateTime in Flutter?

We can get Year, Month, and day from Given DateTime by

DateTime dateTime=DateTime.now();
getYear()
{
  return dateTime.year;
}

getMonth()
{
  return dateTime.month;
}
getDay()
{
  return dateTime.day;
}

 

How to get Hour, Minute, and Seconds from DateTime in Flutter?

Get Hour, Minute, and Seconds by

getHour()
{
  return dateTime.hour;
}

getMinute()
{
  return dateTime.minute;
}

getseconds()
{
  return dateTime.second;
}

 

How to Customize your Own DateTime Picker Model

Create a class and extends it with CommonPickerModel and we can update whichever we want to customize components for DateTimepicker

class CustomPicker extends CommonPickerModel {
  String digits(int value, int length) {
    return '$value'.padLeft(length, "0");
  }
  CustomPicker({DateTime currentTime, LocaleType locale}) : super(locale: locale) {
    this.currentTime = currentTime ?? DateTime.now();
    this.setLeftIndex(this.currentTime.hour);
    this.setMiddleIndex(this.currentTime.minute);
    this.setRightIndex(this.currentTime.second);
  }
  @override
  String leftStringAtIndex(int index) {
    if (index >= 0 && index < 24) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }
  @override
  String middleStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }
  @override
  String rightStringAtIndex(int index) {
    if (index >= 0 && index < 60) {
      return this.digits(index, 2);
    } else {
      return null;
    }
  }
  @override
  String leftDivider() {
    return "|";
  }
  @override
  String rightDivider() {
    return "|";
  }
  @override
  List<int> layoutProportions() {
    return [1, 2, 1];
  }
  @override
  DateTime finalTime() {
    return currentTime.isUtc
        ? DateTime.utc(currentTime.year, currentTime.month, currentTime.day,
        this.currentLeftIndex(), this.currentMiddleIndex(), this.currentRightIndex())
        : DateTime(currentTime.year, currentTime.month, currentTime.day, this.currentLeftIndex(),
        this.currentMiddleIndex(), this.currentRightIndex());
  }
}

 

Find the DateTimePIcker plugin here

 

Tags: Flutter DateTime Picker, Convert String to DateTime, Get Year from DateTime in Flutter

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

2168 Views