I'm trying to find out the difference between two timestamps in Hours, Minutes, and Seconds and have managed to chalk out the below code to achieve the same. However, I don't seem to be getting the correct output. Can anyone please tell me where it is that I'm going wrong?
import 'package:intl/intl.dart';
void main() {
String date = '2022-12-05 23:02:20';
var stored =
DateTime.parse(DateFormat('yyyy-mm-dd hh:mm:ss.ms').format(DateTime.parse(date)));
var now = DateTime.now();
var difference = now.difference(stored).inSeconds;
Duration duration = Duration(seconds: difference);
print('VALUE: $stored');
print('CURRENT TIME: $now');
print(stored.runtimeType);
print('HOURS: ${duration.inHours}');
print('MINUTES: ${duration.inMinutes}');
print('SECONDS: ${duration.inSeconds}');
}
This here is the output that I'm getting:
VALUE: 2022-02-05 11:02:20.220
CURRENT TIME: 2022-12-05 23:44:08.827
DateTime
HOURS: 7284
MINUTES: 437081
SECONDS: 26224908
Common mathematics suggests that the difference between 2022-12-05 23:44:08.827 and 2022-02-05 11:02:20.220 should produce 42 minutes and not 437081. Also, this was written on Dartpad
There are a few things wrong:
DateTime.parse(DateFormat('yyyy-mm-dd hh:mm:ss.ms').format(DateTime.parse(date))); makes no sense. You're taking a String representation of a date/time, parsing it with DateTime.parse to get a DateTime object, then using DateFormat to convert that back to a String so that you can call DateTime.parse on it again. Just use DateTime.parse or DateFormat.parse once.
As Ben explained, you're using the wrong DateFormat pattern. MM should be used for the month number; mm should be used for minutes.
.ms in your DateFormat pattern is also wrong; that means minutes and seconds, not milliseconds. You should use S for fractional seconds. But since you're just parsing a date/time string in an ISO format, you don't need DateFormat at all.
var difference = now.difference(stored).inSeconds;
Duration duration = Duration(seconds: difference);
This also doesn't make much sense. now.difference(stored) already returns a Duration object. There's no point in converting a Duration to a number of seconds back to another a Duration unless you're trying to explicitly discard any fractional seconds.
Common mathematics suggests that the difference between 2022-12-05 23:44:08.827 and 2022-02-05 11:02:20.220 should produce 42 minutes and not 437081.
You seem to expect that Duration.inMinutes should return the minutes component of the duration, but inMinutes returns the total number of minutes. For example, Duration(hours: 1, minutes: 2).inMinutes will return 62, not 2. If you instead want the minutes component, you will need to use something like duration.inMinutes.remainder(60). Same thing applies for Duration.inSeconds.
Here is an adjusted version:
void main() {
String date = '2022-12-05 23:02:20';
var stored = DateTime.parse(date);
var now = DateTime.now();
var duration = now.difference(stored);
print('VALUE: $stored');
print('CURRENT TIME: $now');
print(stored.runtimeType);
print('HOURS: ${duration.inHours}');
print('MINUTES: ${duration.inMinutes.remainder(60)}');
print('SECONDS: ${duration.inSeconds.remainder(60)}');
}
which for me outputs:
VALUE: 2022-12-05 23:02:20.000
CURRENT TIME: 2022-12-05 12:12:37.693
DateTime
HOURS: -10
MINUTES: -49
SECONDS: -42
Note that since the above code currently is subtracting a later time from an earlier time, the resulting difference is a negative Duration, so the output might look a little weird.
You should be using MM instead of mm when parsing the date.
Fixed example:
import 'package:intl/intl.dart';
void main() {
String date = '2022-12-05 23:02:20';
var stored =
DateTime.parse(DateFormat('yyyy-MM-dd hh:mm:ss.ms').format(DateTime.parse(date)));
var now = DateTime.now();
var difference = now.difference(stored).inSeconds;
Duration duration = Duration(seconds: difference);
print('VALUE: $stored');
print('CURRENT TIME: $now');
print(stored.runtimeType);
print('HOURS: ${duration.inHours}');
print('MINUTES: ${duration.inMinutes}');
print('SECONDS: ${duration.inSeconds}');
}
Output (13:29 EST timezone):
VALUE: 2022-12-05 11:02:20.220
CURRENT TIME: 2022-12-05 13:29:06.916
DateTime
HOURS: 2
MINUTES: 146
SECONDS: 8806
Related
I was wondering if I could make an app in which time is display in words instead of conventional numbers. Do you think that there is any package for dart to convert time or numbers to words?
For example
1:30 AM will be One : Thirty AM
Thanks for reading this question. Have a wonderful day.
You can use any of available package to convert from number to words example
package: https://pub.dev/packages/number_to_words
import 'package:number_to_words/number_to_words.dart';
main(){
String input = '1:30 AM';
var s1 = input.split(':');
var s2 = s1[1].split(' ');
String hour = s1[0];
String minute = s2[0];
String hourWord = NumberToWord().convert('en-in',int.parse(hour));
String minuteWord = NumberToWord().convert('en-in',int.parse(minute));
print('$hourWord:$minuteWork ${s2[1]}');
}
I need to set the other object's timezone to match now object which has utc timezone.
I'm comparing two datetime objects but the 'difference' value does not match the expected value. Most likely down to the fact that both objects have different Time Zones (Utc & Bst).
void main() {
var now = new DateTime.now().toUtc();
print(now);
print(now.timeZoneName);
var other = DateTime.parse("2020-05-22 18:27:32.608069");
print(other);
print(other.timeZoneName);
var diff = now.difference(other);
print(diff);
}
output:
2020-05-22 19:26:39.169Z
UTC
2020-05-22 18:27:32.608
British Summer Time
1:59:06.561000
You don't want to convert, you want to read in a date/time as UTC.
Change
var other = DateTime.parse("2020-05-22 18:27:32.608069");
to
var other = DateTime.parse("2020-05-22 18:27:32.608069z");
If other is already constructed, you need to make a new object with DateTime.utc()
https://api.dart.dev/stable/2.8.2/dart-core/DateTime/DateTime.utc.html
var newDate = new DateTime.utc(other.year, other.month, other.day, other.hour, other.minute, other.second, other.millisecond, other.microsecond);
I have an enum type:
enum Day {sunday, monday, tuesday...}
and a variable:
Day day = Day.sunday;
I would like to be able to increment the day. something like this:
day++; // this would be wonderful
day = Day.getByIndex(day.index + 1); // something like this can also work
But I couldn't find anything like this. Is the only option to use a switch on all days?
DartPad example
enum Day {sunday, monday, tuesday}
void main() {
var day = Day.sunday;
print(day);
print(Day.values[day.index + 1]);
}
Dart enums are known to not be very powerful. I guess they'll get some overhaul eventually.
first time here. I'm a beginner student at swift (and programming in general) and I'm trying to make a simple app which will show 5 time values based on current day. I've tried a lot of stuff, but just cannot develop logic here. I will copy paste code (which some of it is pseudocode).
import UIKit
class ViewController: UIViewController {
// TIME Values
let time1 = ["07:01", "07:03", "07:03"] // ..... Array continues for 365 days, every string value representing each day
let time2 = ["11:59", "11:59", "12:00"] // ..... Array continues for 365 days, every string value representing each day
let time3 = ["14:15", "14:16", "14:17"] // ..... Array continues for 365 days, every string value representing each day
let time4 = ["17:12", "17:13", "17:15"] // ..... Array continues for 365 days, every string value representing each day
let time5 = ["19:10", "19:11", "19:12"] // ..... Array continues for 365 days, every string value representing each day
// Current Date
let todaysDate = NSDate()
// Pseudocode to extract the value from time arrays...
choose a value from TIME Values based on todaysDate
print(time1) // single value from time1 array (converted from string to date/time value) based on todaysDate
print(time2) // single value from time1 array (converted from string to date/time value) based on todaysDate
print(time3) // single value from time1 array (converted from string to date/time value) based on todaysDate
print(time4) // single value from time1 array (converted from string to date/time value) based on todaysDate
print(time5) // single value from time1 array (converted from string to date/time value) based on todaysDate
// Final values should be NSDate (or similar) values, because of time manipulation
let timeCorrection1 = ["00:02", "00:03", "00:03"] // ..... Correction continues for 365 days, every string value representing each day
let timeCorrection2 = ["00:02", "00:03", "00:03"] // ..... Correction continues for 365 days, every string value representing each day
let timeCorrection3 = ["00:02", "00:03", "00:03"] // ..... Correction continues for 365 days, every string value representing each day
let timeCorrection4 = ["00:02", "00:03", "00:03"] // ..... Correction continues for 365 days, every string value representing each day
let timeCorrection5 = ["00:02", "00:03", "00:03"] // ..... Correction continues for 365 days, every string value representing each day
override func viewDidLoad() {
super.viewDidLoad()
}
}
So the idea is to get a value from a string array based on currentdate, and have that in nsdate format (in MM:hh style) so it can be manipulated later, since I would like to subtract or add values from other variables (ie 00:02).
I hope I was clear enough, thank you very much in advance!
I need to check a difference between a given date and current date is less than 365days?
i tried some thing like this.
System.TimeSpan diff = DateTime.UtcNow.Subtract((DateTime)customer.LastValidationDate);
result = (diff.Days < 1);
this doesn't seem to work correct for few dates.
i need to achieve:
if given date and current date difference is less-than or equal to 1 year (365 days) return true
else return false.
try this found at stackoverflow
public static int MonthDifference(this DateTime lValue, DateTime rValue)
{
return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year);
}