Flutter: Remove leading zeros from time format
3,285
Solution 1
Try the following
Add intl package to your pubspec.yaml file.
import 'package:intl/intl.dart';
DateFormat dateFormat = DateFormat("HH:mm");
Converting DateTime object to String
DateTime yourDate = DateTime.now());
String string = dateFormat.format(yourDate);
Can also try this
DateTime yourDate = DateTime.now();
String string = new DateFormat.Hm().format(yourDate); // force 24 hour time
Update
To Parse a String to a Date you can use this
DateFormat df = DateFormat('HH:mm:ss');
DateTime dt = df.parse('00:07:00');
String string = DateFormat.Hm().format(dt);
References
Solution 2
Looks like at this point just using a single char (eg, M
instead of MM
) in the format string handles the trim of leading zeroes:
BEFORE:
// Output: 01/01/2021, 02:41 PM
static final dateFormatLeadingZeros = new DateFormat('MM/dd/yyyy, hh:mm a');
AFTER:
// Output: 1/1/2021, 2:41 PM
static final dateFormatTrimmed = new DateFormat('M/d/yyyy, h:mm a');
Author by
selected
Updated on December 14, 2022Comments
-
selected over 1 year
I am receiving a string in this format
'HH:mm:ss'
and I need to get rid of the leading zeros OR convert it to minutes/hours. Is there aRegExp
to achieve this?Examples with no leading zeros:
00:03:15 => 3:15 10:10:10 => 10:10:10 00:00:00 => 0:00 04:00:00 => 4:00:00 00:42:32 => 42:32 00:00:18 => 0:18 00:00:08 => 0:08
Examples of time converted to minutes/hours
00:07:00 => 7 min 00:10:30 => 10:30 min 01:40:00 => 1h 40 min