Noam
Noam

Reputation: 535

How to extract only the time from DateTime.now();

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

Upvotes: 24

Views: 35197

Answers (3)

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

TimeOfDay.fromDateTime(DateTime.now());

Upvotes: 3

raavan199
raavan199

Reputation: 135

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

Upvotes: 2

Tinus Jackson
Tinus Jackson

Reputation: 3653

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

Upvotes: 56

Related Questions