How to format an integer to ss:m - flutter

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

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.

Convert seconds to mm:ss in dart

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);
}

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 Round up the Date-Time nearest to 30 min interval in DART (Flutter)?

I would like to round DateTime to the nearest 30 mins. Is there rounding mechanism provided in DART?
I had a similar problem today and but it was to clamp to the next 15 mins.
DateTime nearestQuarter(DateTime val) {
return DateTime(val.year, val.month, val.day, val.hour,
15, 30, 45, 60][(val.minute / 15).floor()]);
}
or in your case
DateTime nearestHalf(DateTime val) {
return DateTime(val.year, val.month, val.day, val.hour,
[30, 60][(val.minute / 30).floor()]);
}
I just noticed you said 'nearest half hour'
DateTime nearestHalf(DateTime val) {
return DateTime(val.year, val.month, val.day, val.hour,
[0, 30, 60][(val.minute / 30).round()]);
}
https://francescocirillo.com/pages/anti-if-campaign
You can use this function to roundup the time.
DateTime alignDateTime(DateTime dt, Duration alignment,
[bool roundUp = false]) {
assert(alignment >= Duration.zero);
if (alignment == Duration.zero) return dt;
final correction = Duration(
days: 0,
hours: alignment.inDays > 0
? dt.hour
: alignment.inHours > 0
? dt.hour % alignment.inHours
: 0,
minutes: alignment.inHours > 0
? dt.minute
: alignment.inMinutes > 0
? dt.minute % alignment.inMinutes
: 0,
seconds: alignment.inMinutes > 0
? dt.second
: alignment.inSeconds > 0
? dt.second % alignment.inSeconds
: 0,
milliseconds: alignment.inSeconds > 0
? dt.millisecond
: alignment.inMilliseconds > 0
? dt.millisecond % alignment.inMilliseconds
: 0,
microseconds: alignment.inMilliseconds > 0 ? dt.microsecond : 0);
if (correction == Duration.zero) return dt;
final corrected = dt.subtract(correction);
final result = roundUp ? corrected.add(alignment) : corrected;
return result;
}
and then use it the following way
void main() {
DateTime dt = DateTime.now();
var newDate = alignDateTime(dt,Duration(minutes:30));
print(dt); // prints 2022-01-07 15:35:56.288
print(newDate); // prints 2022-01-07 15:30:00.000
}
This function converts a DateTime to the nearest 30 minute mark in a clock. Be warned that this 30 minute mark is obtained with respect to the local time zone of the machine in which this code runs on.
DateTime roundWithin30Minutes(DateTime d) {
final int deltaMinute;
if (d.minute < 15) {
deltaMinute = -d.minute; // go back to zero
} else if (d.minute < 45) {
deltaMinute = 30 - d.minute; // go to 30 minutes
} else {
deltaMinute = 60 - d.minute;
}
return d.add(Duration(
milliseconds: -d.millisecond,
// reset milliseconds to zero
microseconds: -d.microsecond,
// reset microseconds to zero,
seconds: -d.second,
// reset seconds to zero
minutes: deltaMinute));
}
If you are presenting this DateTime in another non local time zone whose offset duration is not a multiple of 30 minutes (eg: Nepal time zone is GMT+5:45) this implementation will not work.
extension DateTimeExt on DateTime {
DateTime get roundMin =>
DateTime(this.year, this.month, this.day, this.hour, () {
if (this.minute <= 15) {
return 0;
} else if (this.minute > 15 && this.minute <= 45) {
return 30;
} else {
return 60;
}
}());
}
You can do It with a simple extension just call it like this
var a = DateTime(2021, 5, 4, 3, 46, 4, 7);
print(a.roundMin);

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.