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
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.
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 .
Try this: String hourMinute = DateTime. Now. ToString("HH:mm");
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With