skip to Main Content

When I do a datetime.now() in Flutter, for example 1:7:6, it shows 1:7:6. We want this to be displayed as 01:07:06.

DateTime now = DateTime.now();

print('${now.year}/${now.month}/${now.day} ${now.hour}:${now.minute}:${now.second}')

result

2023/5/10 1:7:56

2

Answers


  1. You can use:

    DateFormat('yyyy/MM/dd HH:mm:ss').format(DateTime.now())
    

    DateFormat documentation: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html

    Login or Signup to reply.
  2. adding to the answer of @Alaindeseine you can also do it using toString().padLeft() method to pad the hours, minutes, and seconds with leading zeros if necessary:

    Code

    import 'dart:core';
    
    void main() {
      DateTime now = DateTime.now();
    
      // Pad the hours, minutes, and seconds with leading zeros if necessary
      String formattedHour = now.hour.toString().padLeft(2, '0');
      String formattedMinute = now.minute.toString().padLeft(2, '0');
      String formattedSecond = now.second.toString().padLeft(2, '0');
    
      print('${now.year}/${now.month}/${now.day} $formattedHour:$formattedMinute:$formattedSecond');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search