[android] How to format DateTime in Flutter , How to get current time in flutter?

I am trying to display the current DateTime in a Text widget after tapping on a button. The following works, but I'd like to change the format.

Current approach

DateTime now = DateTime.now();
currentTime = new DateTime(now.year, now.month, now.day, now.hour, now.minute);
 Text('$currentTime'), 

Result

YYYY-MM-JJ HH-MM:00.000

Question

How can I remove the :00.000 part?

This question is related to android ios flutter datetime dart

The answer is


You can use DateFormat from intl package.

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);

Add intl package to your pubspec.yaml file.

import 'package:intl/intl.dart';

DateFormat dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss");

Converting DateTime object to String

String string = dateFormat.format(DateTime.now());

Converting String to DateTime object

DateTime dateTime = dateFormat.parse("2019-07-19 8:40:23");

With this approach, there is no need to import any library.

DateTime now = DateTime.now();

String convertedDateTime = "${now.year.toString()}-${now.month.toString().padLeft(2,'0')}-${now.day.toString().padLeft(2,'0')} ${now.hour.toString()}-${now.minute.toString()}";

Output

2020-12-05 14:57


Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below

import 'package:jiffy/jiffy.dart';   

var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");

You can also do the following

var a = Jiffy().yMMMMd; // October 18, 2019

And you can also pass in your DateTime object, A string and an array

var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019

var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019

var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019

Here's my simple solution. That does not require any dependency.

However, the date will be in string format. If you want the time then change the substring values

print(new DateTime.now()
            .toString()
            .substring(0,10)
     );   // 2020-06-10

there is some change since the 0.16 so here how i did,

import in the pubspec.yaml

dependencies:
      flutter:
        sdk: flutter
      intl: ^0.16.1

then use

  txdate= DateTime.now()


  DateFormat.yMMMd().format(txdate)

Use this function

todayDate() {
    var now = new DateTime.now();
    var formatter = new DateFormat('dd-MM-yyyy');
    String formattedTime = DateFormat('kk:mm:a').format(now);
    String formattedDate = formatter.format(now);
    print(formattedTime);
    print(formattedDate);
  }

Output:

08:41:AM
21-12-2019

You can also use this syntax. For YYYY-MM-JJ HH-MM:

var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';

Use String split method to remove :00.000

var formatedTime = currentTime.toString().split(':')
Text(formatedTime[0])

======= OR USE BELOW code for YYYY-MM-DD HH:MM:SS format without using library ====

var stringList =  DateTime.now().toIso8601String().split(new RegExp(r"[T\.]"));
var formatedDate = "${stringList[0]} ${stringList[1]}";

Questions with android tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8? "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' GoogleMaps API KEY for testing Can I use library that used android support with Androidx projects. How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Android Material and appcompat Manifest merger failed Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 How to format DateTime in Flutter , How to get current time in flutter? How to change package name in flutter? Failed to resolve: com.android.support:appcompat-v7:28.0 What is AndroidX? Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve FirebaseInstanceIdService is deprecated installation app blocked by play protect Handling back button in Android Navigation Component Android design support library for API 28 (P) not working Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Install Android App Bundle on device Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. How to develop Android app completely using python? Invoke-customs are only supported starting with android 0 --min-api 26 Flutter.io Android License Status Unknown How to open Android Device Monitor in latest Android Studio 3.1 Default interface methods are only supported starting with Android N How can I change the app display name build with Flutter? Error:(9, 5) error: resource android:attr/dialogCornerRadius not found error: resource android:attr/fontVariationSettings not found Flutter does not find android sdk Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0) Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior flutter run: No connected devices Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6 Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation' PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Questions with ios tag:

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64 iPhone is not available. Please reconnect the device Is it possible to opt-out of dark mode on iOS 13? Make a VStack fill the width of the screen in SwiftUI Presenting modal in iOS 13 fullscreen The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1 Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Xcode 10: A valid provisioning profile for this executable was not found Xcode 10, Command CodeSign failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 How to format DateTime in Flutter , How to get current time in flutter? Xcode couldn't find any provisioning profiles matching How can I change the app display name build with Flutter? Convert Json string to Json object in Swift 4 Distribution certificate / private key not installed Get safe area inset top and bottom heights Error ITMS-90717: "Invalid App Store Icon" iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone" Cordova app not displaying correctly on iPhone X (Simulator) Detect if the device is iPhone X Xcode 9 error: "iPhone has denied the launch request" No signing certificate "iOS Distribution" found iOS 11, 12, and 13 installed certificates not trusted automatically (self signed) com.apple.WebKit.WebContent drops 113 error: Could not find specified service Safe Area of Xcode 9 How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc? What are my options for storing data when using React Native? (iOS and Android) Xcode Error: "The app ID cannot be registered to your development team." Open Url in default web browser Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 HTML5 Video autoplay on iPhone Swift error : signal SIGABRT how to solve it What is the meaning of 'No bundle URL present' in react-native? Convert NSDate to String in iOS Swift How can I regenerate ios folder in React Native project? `React/RCTBridgeModule.h` file not found Removing object from array in Swift 3 I get conflicting provisioning settings error when I try to archive to submit an iOS app

Questions with flutter tag:

Flutter Countdown Timer How to make an AlertDialog in Flutter? FlutterError: Unable to load asset Set the space between Elements in Row Flutter Flutter: RenderBox was not laid out Space between Column's children in Flutter How to change status bar color in Flutter? How can I add shadow to the widget in flutter? Flutter - The method was called on null Flutter- wrapping text Flutter plugin not installed error;. When running flutter doctor How to scroll page in flutter Waiting for another flutter command to release the startup lock Under which circumstances textAlign property works in Flutter? How to format DateTime in Flutter , How to get current time in flutter? Flutter : Vertically center column How to change package name in flutter? Rounded Corners Image in Flutter How do you change the value inside of a textfield flutter? Flutter: Setting the height of the AppBar How to add image in Flutter Flutter position stack widget in center Custom Card Shape Flutter SDK Flutter command not found Dart/Flutter : Converting timestamp How do I center text vertically and horizontally in Flutter? Flutter Circle Design Iterating through a list to render multiple widgets in Flutter? How to change TextField's height and width? How to set the width of a RaisedButton in Flutter? HTTP POST with Json on Body - Flutter/Dart How to find the path of Flutter SDK Not able to change TextField Border Color Create a button with rounded border How do I use hexadecimal color strings in Flutter? Button Width Match Parent flutter corner radius with transparent background Create a rounded button / button with border-radius in Flutter Dart: mapping a list (list.map) How to create a circle icon button in Flutter? Flutter.io Android License Status Unknown How to use conditional statement within child attribute of a Flutter Widget (Center Widget) How to make flutter app responsive according to different screen size? Check whether there is an Internet connection available on Flutter app How to create number input field in Flutter? How to Determine the Screen Height and Width in Flutter How to run code after some delay in Flutter? Flutter: Run method on Widget build complete Round button with text and icon in flutter How can I change the app display name build with Flutter?

Questions with datetime tag:

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")? How do I filter date range in DataTables? Convert a string to datetime in PowerShell How to insert current datetime in postgresql insert query How to change the datetime format in pandas Pandas: Subtracting two date columns and the result being an integer finding first day of the month in python Error in MySQL when setting default value for DATE or DATETIME How to Extract Year from DATE in POSTGRESQL java.time.format.DateTimeParseException: Text could not be parsed at index 21 How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds? Is there a simple way to increment a datetime object one month in Python? Pandas: Convert Timestamp to datetime.date How to insert date values into table In Oracle SQL: How do you insert the current date + time into a table? Getting today's date in YYYY-MM-DD in Python? What's the difference between Instant and LocalDateTime? How to convert string to datetime format in pandas python? What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types Format datetime to YYYY-MM-DD HH:mm:ss in moment.js How to convert an Instant to a date format? Python - Get Yesterday's date as a string in YYYY-MM-DD format python pandas extract year from datetime: df['year'] = df['date'].year is not working Create a day-of-week column in a Pandas dataframe using Python datetime to string with series in python pandas How to get current time in python and break up into year, month, day, hour, minute? How to force the input date format to dd/mm/yyyy? What exactly does the T and Z mean in timestamp? How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query How do I get the current timezone name in Postgres 9.3? Datetime current year and month in Python How to convert datetime to integer in python Convert Pandas Series to DateTime in a DataFrame Extract time from moment js object Get current date in DD-Mon-YYY format in JavaScript/Jquery Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8) How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe? Calculate time difference in minutes in SQL Server Convert Pandas Column to DateTime Inserting created_at data with Laravel

Questions with dart tag:

How to integrate Dart into a Rails app Flutter Countdown Timer How to make an AlertDialog in Flutter? Set the space between Elements in Row Flutter Flutter: RenderBox was not laid out Space between Column's children in Flutter How to change status bar color in Flutter? How can I add shadow to the widget in flutter? Flutter - The method was called on null Flutter- wrapping text Flutter plugin not installed error;. When running flutter doctor How to scroll page in flutter How to format DateTime in Flutter , How to get current time in flutter? How to change package name in flutter? How do you change the value inside of a textfield flutter? Flutter: Setting the height of the AppBar How to add image in Flutter Flutter position stack widget in center Flutter command not found Dart/Flutter : Converting timestamp Flutter Circle Design Iterating through a list to render multiple widgets in Flutter? HTTP POST with Json on Body - Flutter/Dart Not able to change TextField Border Color How do I use hexadecimal color strings in Flutter? flutter corner radius with transparent background Create a rounded button / button with border-radius in Flutter Dart: mapping a list (list.map) How to use conditional statement within child attribute of a Flutter Widget (Center Widget) How to make flutter app responsive according to different screen size? Check whether there is an Internet connection available on Flutter app How to create number input field in Flutter? How to Determine the Screen Height and Width in Flutter Flutter: Run method on Widget build complete How can I change the app display name build with Flutter? How do I disable a Button in Flutter? How to set up devices for VS Code for a Flutter emulator How to clear Flutter's Build cache? How to implement drop down list in flutter? Flutter: how to make a TextField with HintText but no Underline? Dart SDK is not configured How to add a border to a widget in Flutter? How to work with progress indicator in flutter? How to create Toast in Flutter? How to add a ListView to a Column in Flutter? How can I dismiss the on screen keyboard? Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart' Flutter - Wrap text on overflow, like insert ellipsis or fade Show/hide widgets in Flutter programmatically Flutter - Layout a Grid