Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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

like image 746
Noam Avatar asked Jun 03 '19 12:06

Noam


People also ask

How do I get just the time from DateTime?

To extract time only from datetime with formula, you just need to do as follow: 1. Select a blank cell, and type this formula =TIME(HOUR(A1),MINUTE(A1), SECOND(A1)) (A1 is the first cell of the list you want to extract time from), press Enter button and drag the fill handle to fill range.

How do you get just the time from a DateTime in Python?

We can get a datetime object using the strptime() method by passing the string which contains date and time and get a datetime object. We can then get the hour and minute from the datetime object by its . hour and .

How do I get only hour and minutes from DateTime?

Try this: String hourMinute = DateTime. Now. ToString("HH:mm");


Video Answer


2 Answers

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
like image 101
Tinus Jackson Avatar answered Oct 17 '22 10:10

Tinus Jackson


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
like image 42
raavan199 Avatar answered Oct 17 '22 08:10

raavan199