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";
}
Related
Can anyone give me some guidance or tips about better dart programming for my code below?
Can it be more simpler?
I think it's not good enough, and I also have a question about 'if statement' construction which i added inside the code.
void main() {
int month = 12;
int day = 1;
int year = 2022;
int newDay;
int newMonth;
int newYear;
Calculate calculate = Calculate(day,month,year);
newDay = calculate.newDay;
newMonth = calculate.newMonth;
newYear = calculate.newYear;
if (newMonth > 7) {
newYear +=1;}
print('New date is : $newDay / $newMonth / $newYear');
}
class Calculate{
int month;
int day;
int year;
Calculate(this.day, this.month, this.year);
get newDay => day + 7;
get newMonth => month + 1;
get newYear => year + 1;
//QUESTION.. how to construct below 'if statement' within this class?
//if newMonth > 7 then newYear += 1;
}
I make some changes to remove the classes, but i can't return the value, please help how to fix this :
void main() {
int month = 12;
int day = 1;
int year = 2022;
print(Calculate(day,month,year));
}
Calculate(day,month,year){
int newday = 0;
int newmonth = 0 ;
int newyear = 0;
newday = day + 7;
newmonth = month + 1;
newyear = year + 1;
List<int> result;
if (month > 3) {
return '$newday/$newmonth/$newyear';}
else {return '$newday/$newmonth/$newyear+1';}
}
Not really understand what you want to do, but here is a little example. You can play with it and change your preferences.
void main() {
DateData data = DateData(day: 5, month: 12, year: 2022);
DateData newData = DateData(day: data.day, month: 8, year: 2022)
.calculateYear()
.calculateMonth()
.calculateDay();
print(data.toString());
print(newData.toString());
}
class DateData {
DateData({
required this.day,
required this.month,
required this.year,
});
int day;
int month;
int year;
#override
String toString() => 'DateData(day: $day, month: $month, year: $year)';
DateData calculateYear() {
// Do something with `year` value.
if (month > 7) {
year += 1;
}
return this;
}
DateData calculateDay() {
// Do something with `day` value.
if (day > 31) {
day = 1;
}
return this;
}
DateData calculateMonth() {
// Do something with `month` value.
if (month > 12) {
month = 1;
}
return this;
}
}
You should replace your Calculate class with a function. There is no need for a class here.
So i have small double values and i need to convert them into string in order to display in my app. But i care only about first two significant digits.
It should work like this:
convert(0.000000000003214324) = '0.0000000000032';
convert(0.000003415303) = '0.0000034';
We can convert double to string, then check every index and take up to two nonzero (also .) strings. But the issue comes on scientific notation for long double.
You can check Convert long double to string without scientific notation (Dart)
We need to find exact String value in this case. I'm taking help from this answer.
String convert(String number) {
String result = '';
int maxNonZeroDigit = 2;
for (int i = 0; maxNonZeroDigit > 0 && i < number.length; i++) {
result += (number[i]);
if (number[i] != '0' && number[i] != '.') {
maxNonZeroDigit -= 1;
}
}
return result;
}
String toExact(double value) {
var sign = "";
if (value < 0) {
value = -value;
sign = "-";
}
var string = value.toString();
var e = string.lastIndexOf('e');
if (e < 0) return "$sign$string";
assert(string.indexOf('.') == 1);
var offset =
int.parse(string.substring(e + (string.startsWith('-', e + 1) ? 1 : 2)));
var digits = string.substring(0, 1) + string.substring(2, e);
if (offset < 0) {
return "${sign}0.${"0" * ~offset}$digits";
}
if (offset > 0) {
if (offset >= digits.length) return sign + digits.padRight(offset + 1, "0");
return "$sign${digits.substring(0, offset + 1)}"
".${digits.substring(offset + 1)}";
}
return digits;
}
void main() {
final num1 = 0.000000000003214324;
final num2 = 0.000003415303;
final v1 = convert(toExact(num1));
final v2 = convert(toExact(num2));
print("num 1 $v1 num2 $v2");
}
Run on dartPad
I would like to compare last_uploaded_time with current time.
How to check whether the two time is more or less than one minute?
bool compareTime(String starts) {
print(starts);
var start = starts.split(":");
DateTime currentDateTime = DateTime.now();
String currentTime =
DateFormat(DateUtil.TIME_FORMAT).format(currentDateTime);
print(currentTime);
var end = currentTime.split(":");
DateTime initDateTime = DateTime(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
var startDate = (initDateTime.add(Duration(hours: int.parse(start[0]))))
.add(Duration(minutes: int.parse(start[1])));
var endDate = (initDateTime.add(Duration(hours: int.parse(end[0]))))
.add(Duration(minutes: int.parse(end[1])));
if (currentDateTime.isBefore(endDate) &&
currentDateTime.isAfter(startDate)) {
print("CURRENT datetime is between START and END datetime");
return true;
} else {
print("NOT BETWEEN");
return false;
}
}
Output
I/flutter (12908): 01:16
I/flutter (12908): 01:40
I/flutter (12908): NOT BETWEEN
difference
not exactly working with minutes and seconds so you can use some custom algorithm like
import 'package:intl/intl.dart';
class IntelModel { static String timeSinceDate(DateTime date) {
final now = DateTime.now();
final difference = now.toLocal().difference(date.toLocal());
if ((now.day - date.day) >= 8) {
return 'A few weeks ago';
} else if ((now.day - date.day) >= 1) {
return '${(now.day - date.day)} days ago';
} else if (now.day == date.day) {
if (now.hour > date.hour) {
if ((now.hour - date.hour) >= 2) {
if (now.minute == date.minute) {
return '${(now.hour - date.hour)} hours ago';
} else {
var mins = now.minute - date.minute;
if (mins > 1) {
return '${(now.hour - date.hour)} h ${(now.minute - date.minute)} minutes ago';
} else {
return '${(now.hour - date.hour) - 1} h ${60 + mins} minutes ago';
}
}
} else if ((now.hour - date.hour) == 1) {
int timeMin = now.minute + (60 - date.minute);
if (timeMin == 60) {
return '1 hours ago';
} else if (timeMin >= 60) {
return '1 h ${timeMin - 60} mins ago';
} else {
return '$timeMin minutes ago';
}
}
} else if (now.hour == date.hour) {
if (now.minute > date.minute) {
return '${(now.minute - date.minute)} minutes ago';
} else if (date.minute == now.minute) {
return '${(now.second - date.second)} seconds ago';
}
}
} else {
return 'Error in time';
} } }
void main() {
String getDifference(DateTime date){
Duration duration = DateTime.now().difference(date);
String differenceInMinutes = (duration.inMinutes).toString();
return differenceInMinutes;
}
String str = getDifference(DateTime.parse('2021-09-24'));
print (str);
}
i tried above code on dartpad, you can use this to compare tow dateTime variables. As per above example, you can get more options to compare for eg duration.inDays,duration.inHours,duration.inSeconds etc.
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
I need to calculate number of days between two dates in Dart.
There is built in function for that.
leaveEndDate.difference(leaveStartDate).inDays
But I do not want weekends to be included.
Is there any way I can traverse between these 2 Dates or I can just exclude weekends.
I think you have no other choice than looping through all the days to check if this is a weekend day or not :
void main() {
DateTime date1 = DateTime(2019, 12, 01);
DateTime date2 = DateTime(2019, 12, 31);
print(getDifferenceWithoutWeekends(date1, date2));
}
int getDifferenceWithoutWeekends(DateTime startDate, DateTime endDate) {
int nbDays = 0;
DateTime currentDay = startDate;
while (currentDay.isBefore(endDate)) {
currentDay = currentDay.add(Duration(days: 1));
if (currentDay.weekday != DateTime.saturday && currentDay.weekday != DateTime.sunday) {
nbDays += 1;
}
}
return nbDays;
}
Result :
22
EDIT :
Another solution, not sure it is faster but can be useful if you need to identify the dates (you could return list<DateTime> instead of List<int> to see which day is a weekend day).
Here I build each days between the 2 dates and return 1 if this is not a weekend day, then sum the list :
void main() {
DateTime startDate = DateTime(2019, 12, 01);
DateTime endDate = DateTime(2019, 12, 31);
int nbDays = endDate.difference(startDate).inDays + 1;
List<int> days = List.generate(nbDays, (index) {
int weekDay = DateTime(startDate.year, startDate.month, startDate.day + (index)).weekday;
if (weekDay != DateTime.saturday && weekDay != DateTime.sunday) {
return 1;
}
return 0;
});
print(days.reduce((a, b) => a + b));
}
I have also prepared a function which will traverse to all dates between two dates in Dart and will calculate number of days inBetween.
int calculateDaysBetween(DateTime mStartDate, DateTime mEndDate) {
int leaveDays = mEndDate.difference(mStartDate).inDays + 1;
int leaveBalance = 0;
var mTempDateTime =
DateTime(mStartDate.year, mStartDate.month, mStartDate.day);
for (int i = 0; i < leaveDays; i++) {
mTempDateTime = DateTime(
mTempDateTime.year, mTempDateTime.month, mTempDateTime.day + 1);
if (mTempDateTime.weekday == DateTime.friday ||
mTempDateTime.weekday == DateTime.saturday) {
print('is weekend');
} else {
leaveBalance++;
}
print(mTempDateTime);
}
// Total number of days between two dates excluding weekends.
return leaveBalance;
}
Improve #Developine Answer and make it more reusable , I make 2 function.
1.Calculate Total Days Of Month
2.Calculate TotalWeekDayOfMonth
Get Total Days Of Month
int totalDaysOfMonth(int month, int year) {
final result = (month < 12) ? DateTime(year, month + 1, 0) : DateTime(year + 1, 1, 0);
return result.day;
}
Get Total WeekDay Of Month
int totalWeekDayOfMonth(int year, int month, {int day = 1}) {
int totalDayOfMonth = totalDaysOfMonth(year, month);
int result = 0;
DateTime tempDateTime = DateTime(year, month, day);
for (int i = day; i <= totalDayOfMonth; i++) {
tempDateTime = DateTime(tempDateTime.year, tempDateTime.month, i);
if (tempDateTime.weekday == DateTime.saturday || tempDateTime.weekday == DateTime.sunday) {
print('is weekend');
} else {
result++;
}
}
return result;
}
How To Use It
void main(){
final resultWithoutDay = totalWeekDayOfMonth(2019,12);
final resultWithDay = totalWeekDayOfMonth(2019,12,day: 16);
print("Without Day $resultWithoutDay"); // 22
print("With Day $resultWithDay"); // 12
}