What data type is used in dart instead of the TimeSpan data type in C#?
It is Duration.
For example:
void main(List<String> args) {
// Define two dates.
DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15);
DateTime date2 = new DateTime(2010, 8, 18, 13, 30, 30);
// Calculate the interval between the two dates.
Duration interval = date2.difference(date1);
print('$date2 - $date1 = $interval');
// Display individual properties of the resulting TimeSpan object.
print('Total Number of Days: ${interval.inDays}');
print('Total Number of Hours: ${interval.inHours}');
print('Total Number of Minutes: ${interval.inMinutes}');
print('Total Number of Seconds: ${interval.inSeconds}');
print('Total Number of Milliseconds: ${interval.inMilliseconds}');
}
the result will be:
2010-08-18 13:30:30.000 - 2010-01-01 08:00:15.000 = 5501:30:15.000000
Total Number of Days: 229
Total Number of Hours: 5501
Total Number of Minutes: 330090
Total Number of Seconds: 19805415
Total Number of Milliseconds: 19805415000
Related
For example, if times is given as 1.05 seconds, we need to convert it as 00:01:05.
How can we achieve this in Flutter?
Also, if a time is given as duration in milliseconds, how do we convert it to the 00:00:00 format?
You just need some simple integer maths to separate the duration into the units you want and some string formatting to make sure that single-digit numbers get leading zeros.
String formatForVideo(Duration d) {
final millis = d.inMilliseconds;
if (millis >= 3600000) {
throw FormatException('too big to format');
}
final minutes = _pad2(d.inMinutes);
final seconds = _pad2(d.inSeconds % 60);
final cents = _pad2((millis % 1000) ~/ 10);
return '$minutes:$seconds.$cents';
}
String _pad2(int i) => i.toString().padLeft(2, '0');
Which gives expected results:
print(formatForVideo(Duration(minutes: 0, seconds: 1, milliseconds: 50))); // 00:01.05
print(formatForVideo(Duration(minutes: 9, seconds: 51, milliseconds: 50))); // 09:51.05
print(formatForVideo(Duration(minutes:60))); // exception
The output of this definition => 00:00:00
DateTime time = DateTime(1990, 1, 1, 0, 0, 0, 0, 0);
Then when you want to add a period to this time
time.add(const Duration(seconds: 100,milliseconds:200))
and for output =>
String timeString = DateFormat.Hms().format(time);
print(timeString);
Result =>> 00:01:40
I have a list of timing for the appointment but I couldn't divide the time into 15-minute steps. This is what I want to achieve.
Time: 6 AM - 8AM to this format: 06:00 -> 06: 15 -> 06:30 -> 06:45-> 07:00 and so on.
I tried but couldn't do it. Any help will be appreciated.
Do you mean something like this?
DateTime now = new DateTime.now();
DateTime first = new DateTime(now.year, now.month, now.day, 6); // today 6AM
final numberOfSlots = 2 * 4 + 1; // 2 hours * 4 (15 minutes) + 1 to go from 6 to 8
final list = List.generate(
numberOfSlots,
(index) => first.add(Duration(minutes: index * 15)),
);
print(list);
I have the time in datetime format like below. I would like to extract the time from '20-Apr-2020 11:20:10' till '20-Apr-2020 12:40:50'. Do I need it to convert it first to datenumber or I can do it directly here?
Time_datenum={'20-Apr-2020 11:06:00','20-Apr-2020 11:20:10','20-Apr-2020 11:45:30','20-Apr-
2020 12:07:00','20-Apr-2020 12:35:40','20-Apr-2020 12:40:50','20-Apr-2020 13:07:00'};
Time_datetime = datetime(Time_One,'InputFormat','dd-MM-yyyy HH:mm:ss');
Time_datenum={'20-Apr-2020 11:06:00','20-Apr-2020 11:20:10','20-Apr-2020 11:45:30',...
'20-Apr-2020 12:07:00','20-Apr-2020 12:35:40','20-Apr-2020 12:40:50','20-Apr-2020 13:07:00'};
% Create a datetime array from a cell array of character vectors.
Time_datetime = datetime(Time_datenum, 'InputFormat', 'dd-MM-yyyy HH:mm:ss', 'Locale', 'en_GB');
% t = datetime(Year, Month, Day, Hour, Minute, Second)
Time_start = datetime(2020, 4, 20, 11, 20, 10);
Time_end = datetime(2020, 4, 20, 12, 40, 50);
% Extract the time.
Time_extracted = Time_datetime(Time_start <= Time_datetime & Time_datetime <= Time_end);
I am having issues getting my code to work. I am trying to create 30 minutes slots in Swift, but it seems to randomly jump an hour every so often. See code below:
let calendar = Calendar.current
var hour = 07
var hour2 = 07
var minute = 0
var timeLoop = 1
var startDate = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: editedDate)
var endDate = calendar.date(bySettingHour: hour2, minute: 0, second: 0, of: editedDate)
repeat {
if(timeLoop % 2 == 0){
startDate = calendar.date(bySettingHour: hour2, minute: 30, second: 0, of: editedDate)
endDate = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: editedDate)
}
else {
startDate = calendar.date(bySettingHour: hour2, minute: 0, second: 0, of: editedDate)
endDate = calendar.date(bySettingHour: hour2, minute: 30, second: 0, of: editedDate)
}
if (timeLoop == 1) {
startDate = calendar.date(bySettingHour: hour, minute: 0, second: 0, of: editedDate)
endDate = calendar.date(bySettingHour: hour, minute: 30, second: 0, of: editedDate)
}
let eventDate = EventDate()
eventDate.startDate = startDate!
eventDate.endDate = endDate!
self.suggestedDates.append(eventDate)
self.suggestedDates.sort(by: {$0.startDate < $1.startDate}) //Recheck this
//Only need to add this once for day purposes
if (hour == 07) {
self.allDayDates.append(eventDate)
self.allDayDates.sort(by: {$0.startDate < $1.startDate}) //Recheck this
}
//update hours
hour2 = hour
hour += 1
timeLoop += 1
} while hour <= 21
This gives the following results
07:00 - 07:30,
07:30 - 08:00,
08:00 - 08:30,
09:30 - 10:00,
10:00 - 10:30,
11:30 - 12:00,
12:00 - 12:30,
13:30 - 14:00,
As you can see theres a jump from 10:30 to 11:30.
Your code does not give enough idea of what you are trying to do.
However to get the time slots you can do something like this:
let calendar = Calendar.current
let startHour = 07 // Hour from where you want to start the slots
var hourCounter = 07 // Hour counter for looping
let slotDuration = 30 // Constant for duration of slots
let editedDate = Date() // The selected date, as per your code
// Create the start date by setting hour value to the `startHour` of `editedDate`
var startDate = calendar.date(bySettingHour: startHour, minute: 0, second: 0, of: editedDate)
// Assign the same value to endDate as the initial value
var endDate = startDate
repeat {
// Assign the end date to the start date,
// This will get you the slot start duration from earlier slot's end date
// For example,
// If this is the starting slot,
// then the startDate and endDate will be same, as per above code.
// If this is any subsequent slot,
// then the slot should start from the last slot's endDate.
// i.e. if previous slot was 01:30 - 2:00,
// then current slot should start from 2:00.
startDate = endDate
if let date = startDate {
// Get the new endDate by adding your slot duration to the startDate
endDate = calendar.date(byAdding: .minute, value: slotDuration, to: date)
}
// ...
// Do whatever you want to do with these slot values here...
// ...
// Increment the counter for looping
hourCounter += 1
} while hourCounter <= 21
The code generates time slots based on the slot duration. You can change the slotDuration to any desired value (in minute), and it will generate slots accordingly. Try changing it from 30 to 15 and see the results.
There are numerous answers given but I am unable to find compatible with my situation. I need to find difference of 8 hours in time as well as on date change too. Like if time is greater then 8 hours then do not execute something .
Do we have any method which achieve the same in LocalDateTime in Java-8?
I have tried to use following but unable to achieve the same.
LocalDateTime fromDateTime = LocalDateTime.of(2017, 07, 07, 07, 00, 55);
LocalDateTime toDateTime = LocalDateTime.now();
LocalDateTime tempDateTime = LocalDateTime.from(fromDateTime);
long years = tempDateTime.until(toDateTime, ChronoUnit.YEARS);
tempDateTime = tempDateTime.plusYears(years);
long months = tempDateTime.until(toDateTime, ChronoUnit.MONTHS);
tempDateTime = tempDateTime.plusMonths(months);
long days = tempDateTime.until(toDateTime, ChronoUnit.DAYS);
tempDateTime = tempDateTime.plusDays(days);
long hours = tempDateTime.until(toDateTime, ChronoUnit.HOURS);
tempDateTime = tempDateTime.plusHours(hours);
long minutes = tempDateTime.until(toDateTime, ChronoUnit.MINUTES);
tempDateTime = tempDateTime.plusMinutes(minutes);
long seconds = tempDateTime.until(toDateTime, ChronoUnit.SECONDS);
System.out.println("" + java.time.Duration.between(tempDateTime, toDateTime).toHours());
System.out.println(years + " years "
+ months + " months "
+ days + " days "
+ hours + " hours "
+ minutes + " minutes "
+ seconds + " seconds.");
It is difficult to check on time and date separately.
Initially I coded it like but it does not looks correct:
return openBrat!=null
&& openBrat.until(LocalDateTime.now(), ChronoUnit.DAYS) == 0 &&
openBrat.until(LocalDateTime.now(), ChronoUnit.HOURS) >= 8
&& openBrat.until(LocalDateTime.now(), ChronoUnit.Minutes) >= 0;
Could anyone please suggest how to subtract like:
2017 07 06 23:30:00 - 2017 07 07 01:30:00 - Should return 2 hours.
The following prints 2, just like you'd expect.
LocalDateTime ldt1 = LocalDateTime.of(2017, 07, 06, 23, 30, 00);
LocalDateTime ldt2 = LocalDateTime.of(2017, 07, 07, 1, 30, 00);
System.out.println(Duration.between(ldt1, ldt2).toHours());
There is nothing wrong with your code. If you don't get the outcome you expect, you may need to check if your expectation is correct.
To do something when the difference is less than 8 hours, you can do something like this:
LocalDateTime ldt1 = LocalDateTime.of(2017, 07, 06, 23, 30, 00);
LocalDateTime ldt2 = LocalDateTime.of(2017, 07, 07, 1, 30, 00);
Duration d1 = Duration.between(ldt1, ldt2);
Duration d2 = Duration.ofHours(8);
if (d1.compareTo(d2) > 0) {
System.out.println("do nothing");
} else {
System.out.println("do something");
}
My understanding is that you want to get the difference between those 2 dates and "break" it in terms of how many hours, minutes and seconds this difference is.
You can use the Duration class as already explained. But the Duration calculates the difference in seconds and nanoseconds, so you'll have to do some math to get this amount of seconds in separate fields:
LocalDateTime d1 = LocalDateTime.of(2017, 7, 6, 23, 30, 0);
LocalDateTime d2 = LocalDateTime.of(2017, 7, 7, 7, 0, 55);
Duration duration = Duration.between(d1, d2);
// total seconds of difference (using Math.abs to avoid negative values)
long seconds = Math.abs(duration.getSeconds());
long hours = seconds / 3600;
seconds -= (hours * 3600);
long minutes = seconds / 60;
seconds -= (minutes * 60);
System.out.println(hours + " hours " + minutes + " minutes " + seconds + " seconds");
In Java 9 and later, you can call the new Duration::to…Part methods to get number of days, hours, minutes, or seconds rather than calculate the numbers yourself.
The output will be:
7 hours 30 minutes 55 seconds
And the variables hours, minutes and seconds will have the respective values of 7, 30 and 55. If you also want the nanoseconds, just call duration.getNano() to get the respective value (in the example above, it's 0).
If I test with different values:
LocalDateTime d1 = LocalDateTime.of(2017, 7, 6, 23, 30, 0);
LocalDateTime d2 = LocalDateTime.of(2017, 7, 7, 1, 30, 0);
The result will be:
2 hours 0 minutes 0 seconds
If you just want the difference in hours, you can use:
ChronoUnit.HOURS.between(d1, d2);
You can optionally use Math.abs to avoid negative values.
This will return the difference in hours, ignoring the remaining minutes and seconds: in the first example (d2 = LocalDateTime.of(2017, 7, 7, 7, 0, 55)) it will return 7 and in the second example (d2 = LocalDateTime.of(2017, 7, 7, 1, 30, 0)) it will return 2.