2

I have two String inputs date & time. date looks like 12/01/2021 and time looks like 23:00. I want to know an efficient way to convert these into DateTime object using Flutter/Dart.

Currently i am using the following code. It works fine but there must be a better way.

int year = int.parse(date.substring(6));
int month = int.parse(date.substring(0,2));
int day = int.parse(date.substring(3,5));
int hour = int.parse(time.substring(0,2));
int minute = int.parse(time.substring(3,5));
  
final DateTime newDate = DateTime(year,month,day,hour,minute);
Saad Chaudhry
  • 23
  • 1
  • 3

1 Answers1

3

In flutter, we can use DateTime.parse method for this purpose. You just need to pass the string as a particular format.

DateTime.parse("2012-02-27 13:27:00")

Following are some of the accepted string formats.

"2012-02-27 13:27:00" 
"2012-02-27 13:27:00.123456789z" 
"2012-02-27"
"13:27:00,123456789z" 
"20120227 13:27:00" 
"20120227T132700" 
"20120227"
"+20120227" 
"2012-02-27T14Z" 
"2012-02-27T14+00:00"

Following is the flutter example where we convert a string to DateTime.

import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(
       home: Home()
  ));
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
  DateTime dt2 = DateTime.parse("2002-02-27T14:00:00-0500");


  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Convert String to DateTime"),
            backgroundColor: Colors.redAccent,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children:[

                   Text(dt1.toString()),
                   Text(dt2.toString())

                ]
             ),
          )
      );
  }
}

Credits: https://flutterforyou.com/how-to-convert-string-to-datetime-in-flutter/

More links to helpful ressources:

Convert String to DateTime in flutter

Parse string to DateTime in Flutter (Dart)

DEFL
  • 907
  • 7
  • 20