Convert seconds to mm:ss in dart - flutter

I want to convert seconds to minutes and seconds in HH:SS format but my logic don't give me what I want.
static double toMin (var value){
return (value/60);
}
I also want to be able to add the remainder to the minutes value because sometimes my division gives me a seconds value more that 60 which is not accurate

The Duration class can do most of the work for you.
var minutes = Duration(seconds: seconds).inMinutes;
You could generate a String in a mm:ss format by doing:
String formatDuration(int totalSeconds) {
final duration = Duration(seconds: totalSeconds);
final minutes = duration.inMinutes;
final seconds = totalSeconds % 60;
final minutesString = '$minutes'.padLeft(2, '0');
final secondsString = '$seconds'.padLeft(2, '0');
return '$minutesString:$secondsString';
}
That said, I recommend against using a mm:ss format since, without context, it's unclear whether "12:34" represents 12 minutes, 34 seconds or 12 hours, 34 minutes. I suggest instead using 12m34s, which is unambiguous.

you can do something like this:
void main() {
print(toMMSS(100));
}
String toMMSS(int value) =>
'${formatDecimal(value ~/ 60)}:${formatDecimal(value % 60)}';
String formatDecimal(num value) => '$value'.padLeft(2, '0');
or
String toMMSS(int value) =>
'${(value ~/ 60).toString().padLeft(2, '0')}:${(value % 60).toString().padLeft(2, '0')}';
also, you can create an extension on int:
extension DateTimeExtension on int {
String get toMMSS =>
'${(this ~/ 60).toString().padLeft(2, '0')}:${(this % 60).toString().padLeft(2, '0')}';
}
usage:
print(342.toMMSS);

You could try the solution below, this is how I'm doing it:
String formatHHMMSS(int seconds) {
if (seconds != null && seconds != 0) {
int hours = (seconds / 3600).truncate();
seconds = (seconds % 3600).truncate();
int minutes = (seconds / 60).truncate();
String hoursStr = (hours).toString().padLeft(2, '0');
String minutesStr = (minutes).toString().padLeft(2, '0');
String secondsStr = (seconds % 60).toString().padLeft(2, '0');
if (hours == 0) {
return "$minutesStr:$secondsStr";
}
return "$hoursStr:$minutesStr:$secondsStr";
} else {
return "";
}
}

static String formatYMDHMSBySeconds(int milliseconds) {
if (milliseconds == null) {
return '';
}
DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(milliseconds);
return DateFormat("yyyy-MM-dd HH:mm:ss").format(dateTime);
}

Related

how to get difference(remaining time ) between '22:00:00' & '00:22:00' in flutter [duplicate]

I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!
Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.
This is an overview of my code:
.......
class _ActualPositionState extends State<ActualPosition>
with TickerProviderStateMixin {
AnimationController controller;
bool hide = true;
var doc;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
var d = Firestore.instance
.collection('users')
.document(widget.uid);
d.get().then((d) {
if (d.data['parking']) {
setState(() {
hide = false;
});
Firestore.instance
.collection('historyParks')
.where('idUser', isEqualTo: widget.uid)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length == 1) {
for (var i = 0; i < snapshot.documents.length; i++) {
if (snapshot.documents[i].data['date'] ==
DateFormat('EEE d MMM').format(DateTime.now())) {
setState(() {
doc = snapshot.documents[i].data;
});
Duration t = DateTime.parse(snapshot.documents[i].data['until'])
.difference(DateTime.parse(
DateFormat("H:m:s").format(DateTime.now())));
print(t);
}
}
}
});
}
});
controller = AnimationController(
duration: Duration(hours: 1, seconds: 10),
vsync: this,
);
controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
}
double screenHeight;
#override
Widget build(BuildContext context) {
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
.............
you can find the difference between to times by using:
DateTime.now().difference(your_start_time_here);
something like this:
var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.
example from DartPad:
void main() {
final startTime = DateTime(2020, 02, 20, 10, 30);
final currentTime = DateTime.now();
final diff_dy = currentTime.difference(startTime).inDays;
final diff_hr = currentTime.difference(startTime).inHours;
final diff_mn = currentTime.difference(startTime).inMinutes;
final diff_sc = currentTime.difference(startTime).inSeconds;
print(diff_dy);
print(diff_hr);
print(diff_mn);
print(diff_sc);
}
Output: 3,
77,
4639,
278381,
Hope this helped!!
You can use the DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');
Use this code:
var time1 = "14:00";
var time2 = "09:00";
Future<int> getDifference(String time1, String time2) async
{
DateFormat dateFormat = DateFormat("yyyy-MM-dd");
var _date = dateFormat.format(DateTime.now());
DateTime a = DateTime.parse('$_date $time1:00');
DateTime b = DateTime.parse('$_date $time2:00');
print('a $a');
print('b $a');
print("${b.difference(a).inHours}");
print("${b.difference(a).inMinutes}");
print("${b.difference(a).inSeconds}");
return b.difference(a).inHours;
}
To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.
If your goal is to show how long it will be from now to the next specified time in the local timezone:
import 'package:intl/intl.dart';
/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
var now = DateTime.now();
var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
// If the time precedes the current time, treat it as a time for tomorrow.
if (nextTime.isBefore(now)) {
// Note that this is not the same as `nextTime.add(Duration(days: 1))` across
// DST changes.
nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
}
return nextTime.difference(now);
}
void main() {
var timeString = '14:00';
// Format for a 24-hour time. See the [DateFormat] documentation for other
// format specifiers.
var timeFormat = DateFormat('HH:mm');
// Parsing the time as a UTC time is important in case the specified time
// isn't valid for the local timezone on [DateFormat]'s default date.
var time = timeFormat.parse(timeString, true);
print(timeToNext(time.hour, time.minute, time.second));
}
You can use this approch
getTime(time) {
if (!DateTime.now().difference(time).isNegative) {
if (DateTime.now().difference(time).inMinutes < 1) {
return "a few seconds ago";
} else if (DateTime.now().difference(time).inMinutes < 60) {
return "${DateTime.now().difference(time).inMinutes} minutes ago";
} else if (DateTime.now().difference(time).inMinutes < 1440) {
return "${DateTime.now().difference(time).inHours} hours ago";
} else if (DateTime.now().difference(time).inMinutes > 1440) {
return "${DateTime.now().difference(time).inDays} days ago";
}
}
}
And You can call it getTime(time) Where time is DateTime Object.

How to have duration.years and duration.month in flutter?

Hello currently I display a timer with two digit ( DD HH mm SS)
I would like to display a new timer like ( YY MM DD HH)
Here is my current code
String _formatDuration_conso(Duration duration) {
String twoDigits(int n) {
if (n >= 10) return "$n";
return "0$n";
}
String twoDigitHours = twoDigits(duration.inHours.remainder(24));
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return "${twoDigits(duration.inDays)} $twoDigitHours $twoDigitMinutes $twoDigitSeconds";
}
Thank you
Convert days into years
int inYears(int days) {
if (days < 1) return 0;
return days~/365;
}
and then
String _formatDuration_conso(Duration duration) {
//..
return "${twoDigits(inYears(duration.inDays))} ${twoDigits(duration.inDays)} $twoDigitHours $twoDigitMinutes $twoDigitSeconds";
}

How to format an integer to ss:m

I'm trying to get the following format from an int: ss:m (s = seconds, m = milliseconds) from a countdown timer. If there are minutes, the format should be mm:ss:m.
Here's my code:
final int currentTime = 100; // 10 seconds
final Duration duration = Duration(milliseconds: 100);
Timer.periodic(duration, (Timer _timer) {
if (currentTime <= 0) {
_timer.cancel();
} else {
currentTime--;
print(currentTime);
}
});
I tried adding currentTime to a Duration as milliseconds but it didn't give me the desired results. What am I doing wrong and how can I get it to the correct format?
I have used the below method the get it in hh:mm:ss / mm:ss format, you can tweak to get in s:mm
String getTime(int milis) {
Duration position = Duration(milliseconds: milis);
String twoDigits(int n) {
if (n >= 10) return "$n";
return "0$n";
}
String twoDigitMinutes = twoDigits(position.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(position.inSeconds.remainder(60));
String time;
if (twoDigits(position.inHours) == "00") {
time = "$twoDigitMinutes:$twoDigitSeconds";
} else {
time = "${twoDigits(position.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}
return time;
}
try Duration.toString() it'll give you a string formatted in your requirement
more precisely
Duration(milliseconds:currentTime).toString()
and 100 millis is not 10 seconds
10000 millis is 10 seconds

How can I get the difference between 2 times?

I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!
Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.
This is an overview of my code:
.......
class _ActualPositionState extends State<ActualPosition>
with TickerProviderStateMixin {
AnimationController controller;
bool hide = true;
var doc;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
var d = Firestore.instance
.collection('users')
.document(widget.uid);
d.get().then((d) {
if (d.data['parking']) {
setState(() {
hide = false;
});
Firestore.instance
.collection('historyParks')
.where('idUser', isEqualTo: widget.uid)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length == 1) {
for (var i = 0; i < snapshot.documents.length; i++) {
if (snapshot.documents[i].data['date'] ==
DateFormat('EEE d MMM').format(DateTime.now())) {
setState(() {
doc = snapshot.documents[i].data;
});
Duration t = DateTime.parse(snapshot.documents[i].data['until'])
.difference(DateTime.parse(
DateFormat("H:m:s").format(DateTime.now())));
print(t);
}
}
}
});
}
});
controller = AnimationController(
duration: Duration(hours: 1, seconds: 10),
vsync: this,
);
controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
}
double screenHeight;
#override
Widget build(BuildContext context) {
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
.............
you can find the difference between to times by using:
DateTime.now().difference(your_start_time_here);
something like this:
var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.
example from DartPad:
void main() {
final startTime = DateTime(2020, 02, 20, 10, 30);
final currentTime = DateTime.now();
final diff_dy = currentTime.difference(startTime).inDays;
final diff_hr = currentTime.difference(startTime).inHours;
final diff_mn = currentTime.difference(startTime).inMinutes;
final diff_sc = currentTime.difference(startTime).inSeconds;
print(diff_dy);
print(diff_hr);
print(diff_mn);
print(diff_sc);
}
Output: 3,
77,
4639,
278381,
Hope this helped!!
You can use the DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');
Use this code:
var time1 = "14:00";
var time2 = "09:00";
Future<int> getDifference(String time1, String time2) async
{
DateFormat dateFormat = DateFormat("yyyy-MM-dd");
var _date = dateFormat.format(DateTime.now());
DateTime a = DateTime.parse('$_date $time1:00');
DateTime b = DateTime.parse('$_date $time2:00');
print('a $a');
print('b $a');
print("${b.difference(a).inHours}");
print("${b.difference(a).inMinutes}");
print("${b.difference(a).inSeconds}");
return b.difference(a).inHours;
}
To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.
If your goal is to show how long it will be from now to the next specified time in the local timezone:
import 'package:intl/intl.dart';
/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
var now = DateTime.now();
var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
// If the time precedes the current time, treat it as a time for tomorrow.
if (nextTime.isBefore(now)) {
// Note that this is not the same as `nextTime.add(Duration(days: 1))` across
// DST changes.
nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
}
return nextTime.difference(now);
}
void main() {
var timeString = '14:00';
// Format for a 24-hour time. See the [DateFormat] documentation for other
// format specifiers.
var timeFormat = DateFormat('HH:mm');
// Parsing the time as a UTC time is important in case the specified time
// isn't valid for the local timezone on [DateFormat]'s default date.
var time = timeFormat.parse(timeString, true);
print(timeToNext(time.hour, time.minute, time.second));
}
You can use this approch
getTime(time) {
if (!DateTime.now().difference(time).isNegative) {
if (DateTime.now().difference(time).inMinutes < 1) {
return "a few seconds ago";
} else if (DateTime.now().difference(time).inMinutes < 60) {
return "${DateTime.now().difference(time).inMinutes} minutes ago";
} else if (DateTime.now().difference(time).inMinutes < 1440) {
return "${DateTime.now().difference(time).inHours} hours ago";
} else if (DateTime.now().difference(time).inMinutes > 1440) {
return "${DateTime.now().difference(time).inDays} days ago";
}
}
}
And You can call it getTime(time) Where time is DateTime Object.

Flutter double to Time in hours

I'm trying to convert a double value (e.g. 9.5) to a corresponding hour/minute value (e.g. 9.30). I also want to perform calculations using this value, but handle it like a time value (e.g. adding 23 and 2 should result in 1 as the hours should wrap around at 24 hours).
I already tried to convert the value to DateTime, but it says "invalid date format".
This should do it
void main() {
print(getTimeStringFromDouble(9.5)); // 9:30
print(getTimeStringFromDouble(25.0)); // 1:0
}
String getTimeStringFromDouble(double value) {
if (value < 0) return 'Invalid Value';
int flooredValue = value.floor();
double decimalValue = value - flooredValue;
String hourValue = getHourString(flooredValue);
String minuteString = getMinuteString(decimalValue);
return '$hourValue:$minuteString';
}
String getMinuteString(double decimalValue) {
return '${(decimalValue * 60).toInt()}'.padLeft(2, '0');
}
String getHourString(int flooredValue) {
return '${flooredValue % 24}'.padLeft(2, '0');
}