skip to Main Content

I cannot seem to be able to parse the date obtained from DateTime.now() in the hh:mm:ss format. When I do, I get the below error:

Uncaught Error: FormatException: Trying to read : from 2022-12-05 15:40:34.987 at position 5

This here is my code:

import 'package:intl/intl.dart';

void main() {
  var now = DateTime.now();
  DateFormat inputFormat = DateFormat('hh:mm:ss');
  var current = inputFormat.parse(now.toString());
  print(current);
}

I would like to know what I need to do to get the time in the mentioned format.

2

Answers


  1. By using intl package

      var now = DateTime.now();
      DateFormat inputFormat = DateFormat('hh:mm:ss');
      var current = inputFormat.format(now);
      print(current);
    
    Login or Signup to reply.
  2. parse used when you want to convert string to dateTime, but I assume what you want is converting dateTime (now) to string format. you need to use format like this:

    print("date = ${DateFormat.Hms().format(DateTime.now())}"); //date = 14:05:41
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search