I'm trying to write a function to convert a time & date into epoch seconds, it's for a small system that doesn't have the usual time_t library functions. I've got this code below but the calculation is a bit off, can anyone see what's wrong?
long getSecondsSinceEpoch(int h, int m, int s, int day, int month, int year) {
int i,leapDays;
long days;
long seconds;
const static DAYS_IN_MONTH[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
leapDays = 0;
days = (year - 1970) * 365;
for (i = year; i>1970; i--){
if ((i%4)==0) {
leapDays++;
}
}
days += leapDays;
for (i = 1;i < month;i++) {
days += DAYS_IN_MONTH[i - 1];
}
days += day;
seconds = days * 86400;
seconds += (h * 3600);
seconds += (m * 60);
seconds += s;
return seconds;
}
One error is maybe, that you don't take into consideration if you are before February 29th or not when adding the leap days. But I am not sure if this is the only mistake.
EDIT: I think I found the second error: You add all day to days. You should add day - 1 to days, as 08:00 of January 1st is only 8 hours from the start of the month and not 24+8 hours from it.
Related
Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.
Example
For year = 1905, the output should be
solution(year) = 20;
For year = 1700, the output should be
solution(year) = 17.
Input/Output
[execution time limit] 4 seconds (dart)
[input] integer year
A positive integer, designating the year.
Guaranteed constraints:
1 ≤ year ≤ 2005.
[output] integer
The number of the century the year is in.
int getCentury(int year) => (year - 1) ~/ 100 + 1;
is this what you want?
void main() {
int year1 = 1905;
int year2 = 1700;
print('year1 : ${getCentury(year1)}'); //20
print('year2 : ${getCentury(year2)}'); //17
}
int getCentury(int year){
if(1 > year || 2005 < year){
return 0;
}
int century = year ~/ 100;
int temp = year % 100;
if(temp != 0){
century += 1;
}
return century;
}
List<WorkingHourModel> workingHours = response['hours'];
int startTime = int.parse(workingHours[0].startTime.split(':')[0]);
int endTime = int.parse(workingHours[0].endTime.split(':')[0]);
int hoursLeft = endTime - startTime + 1;
List<String> hours =
List.generate(hoursLeft, (i) => '${(endTime - i)}:00').reversed
.toList();
print('Hours-------- $hours');
return {
'success': true,
'hours': hours,
};
}
//this will give the time slots as '1:00', '2:00', '3:00', '4:00'
//Start time will be 1:00 and end time will be 4:00.
Heading
But i need 30 mins breakage, like,
'1:00', '1:30', '2:00', '2:30', '3:00', '3:30', '4:00'
Kindly help..
This should generate the list as you want it:
void main(List<String> args) {
// lets assume 9 to 5
int startTime = 9;
int endTime = 17;
int hoursLeft = endTime - startTime + 1;
final hours = List.generate(hoursLeft * 2, (i) => '${endTime - (i/2).truncate()}:${i%2 == 1 ? '00' : '30'}').reversed.toList();
print('Hours-------- $hours');
}
Hours-------- [9:00, 9:30, 10:00, 10:30, 11:00, 11:30, 12:00, 12:30, 13:00, 13:30, 14:00, 14:30, 15:00, 15:30, 16:00, 16:30, 17:00, 17:30]
Generally speaking, if you have more complicated calculations (what happens if someone works 18:00 to 05:00 in the nightshift?) you may want to use the proper datatypes instead of integers and string concatenation.
from Monday - Thursday, I get the right days, but from Friday, I get the wrong days. Why?
Code example:
Text(DateFormat('EEEE').format(DateTime(DateTime.friday))),
And i get Saturday. Is that a bug?
It's not a bug, DateTime() default constructor takes year as the first argument:
DateTime(int year,
[int month = 1,
int day = 1,
int hour = 0,
int minute = 0,
int second = 0,
int millisecond = 0,
int microsecond = 0])
: this._internal(year, month, day, hour, minute, second, millisecond,
microsecond, false);
So this code:
DateTime date = DateTime(DateTime.friday);
Is essentially constructing a DateTime of the year 5, because DateTime.friday is nothing more than a const int that equals to 5:
static const int monday = 1;
static const int tuesday = 2;
static const int wednesday = 3;
static const int thursday = 4;
static const int friday = 5;
static const int saturday = 6;
static const int sunday = 7;
static const int daysPerWeek = 7;
Formatting with DateFormat returns Saturday which happens to be the first day of the year:
import 'dart:core';
import 'package:intl/intl.dart';
main() {
DateTime date = DateTime(DateTime.friday); // creates a DateTime of the year 5
print(date.year); // year: 5
print(date.month); // month: Jan (default = 1)
print(date.weekday); // day: Saturday (first day of the year)
print("${date.year}-${date.month}-${date.day}"); // 5-1-1
}
DateTime should be used to define a specific Date and Time, for example, Friday 11th Dec 2020, it can't be used to define any Friday.
I am working on an application in flutter where I have to get the difference between two dates in Years, Months and Dates
like below Ex.
final _date1 = DateTime(2019, 10, 15);
final _date2 = DateTime(2020, 12, 20);
Answer Difference = 1 Year, 2 Month, 5 Days
I searched a lot but unfortunately din't get a proper solution to calculate the difference between two dates in Years, Months including leap years.
Note: I know how to get the difference between two dates in Days i.e
final _bd = DateTime(2020, 10, 12);
final _date = DateTime.now();
final _difference = _date.difference(_bd).inDays;
You may customize the following code as per your requirement to return a string or object or make it an extension:
void getDiffYMD(DateTime then, DateTime now) {
int years = now.year - then.year;
int months = now.month - then.month;
int days = now.day - then.day;
if (months < 0 || (months == 0 && days < 0)) {
years--;
months += (days < 0 ? 11 : 12);
}
if (days < 0) {
final monthAgo = DateTime(now.year, now.month - 1, then.day);
days = now.difference(monthAgo).inDays + 1;
}
print('$years years $months months $days days');
}
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.