How to convert String to Date and Date To String in Flutter | Convert datetime to timestamp flutter

Sometimes developers need to Convert Date to String or Convert String to Date in Flutter for done their project. It's very also very important for user interface because always wants to work easily and look good interface.

We will discuss in this blog for both types of Convert String to Date and Date to String. For this first we need a package in " pubspac.yaml" file. The package is date_format.

Dependency for Date Format

dependencies:
    date_format: ^1.0.8


How to use Date Format in Flutter

  1. Add dependency in package file:

    dependencies:
    date_format: ^1.0.8

  2. Install it by using a command or run pubspec.yaml file

    $ pub get

    After this command, if you get exit code 0, that means your Date Time format library successfully added in the project.


  3. Import Library in dart file

    After Installing the dependency in package of date_format then you have to import library file in your dart file.
    import 'package:date_format/date_format.dart';

Date Format
Console Output


1. Convert Date to String Format

void convertStringFromDate() {

  final todayDate = DateTime.now();

  print(formatDate(todayDate, [yyyy, '-', mm, '-', dd, ' ', hh, ':', nn, ':', ss, ' ', am]));

}

Above we are create a function for Convert String Form Date i.e convertStringFromDate().

DateTime.now(); is use for get today date from system, It's inbuilt function of dart.

2. Convert String to Date Format

void convertDateFromString(String strDate){
DateTime todayDate = DateTime.parse(strDate);
print(todayDate);
print(formatDate(todayDate, [yyyy, '/', mm, '/', dd, ' ', hh, ':', nn, ':', ss, ' ', am]));
}

Call above function by convertDateFromString('2018-09-27 13:27:00') and output will be flutter: 2018/09/27 01:09:00 PM

This Date Format we can use for Flutter web application, android application, iOS application and window application.

Example of Date Format

If you need any help then please ask in comment section, Thank you

Previous
Next Post »

1 comments:

Click here for comments
Kaizen
admin
16 November 2020 at 13:31 ×

Fantastyczny tekst Brawo! szczególnie spodobała mi się szata graficzna twojego bloga :-) zapraszam do siebie...

Congrats bro Kaizen you got PERTAMAX...! hehehehe...
Reply
avatar