20

I've this variables to extract the time from DateTime.now();

DateTime date = DateTime.now();
String time = "${date.hour}:${date.minute}:${date.second}";

The problem is if the time for example is 01:09:32, the time that i get is 1:9:32.

How do i get the time with the regular format?

I can do this with if-else, but i'm sure there is a better way

Noam
  • 485
  • 1
  • 7
  • 18
  • 2
    In general, you can do `'$x'.padLeft(2, '0')` to force a string representation of `x` with at least two digits with leading zeroes. – jamesdlin Jun 03 '19 at 17:08

3 Answers3

50

You can try to use a DateFormat, just include intl dependency to your pubspec.yaml

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedTime = DateFormat.Hms().format(now);
print(formattedTime);

Depending on what your requirements is, you can look at DateFormat

Some examples taken from DateFormat-class to help you a bit more.

String formattedTime = DateFormat.jm().format(now);           //5:08 PM
String formattedTime = DateFormat.Hm().format(now);           //17:08  force 24 hour time
Tinus Jackson
  • 3,397
  • 2
  • 25
  • 58
1

Create this function in your Utility Mixin if you have otherwise you can create it in your class also

String getTimeFromDateAndTime(String date) {
    DateTime dateTime;
    try {
      dateTime = DateTime.parse(date).toLocal();
      return DateFormat.jm().format(dateTime).toString(); //5:08 PM
// String formattedTime = DateFormat.Hms().format(now);
// String formattedTime = DateFormat.Hm().format(now);   // //17:08  force 24 hour time
    }
    catch (e) {
    return date;
    }
  }

// In your class

getTimeFromDateAndTime("Pass date in string here")
  • Uncomment format whichever you want from the try part.
  • Use try and catch is a must, because sometime you will get a crash when the format will not match
raavan199
  • 125
  • 1
  • 1
  • 10
0

You can extract it and also use the TimeofDay Object by using this:

TimeOfDay.fromDateTime(DateTime.now());