#Calculating the hours spent sleeping.

27 messages · Page 1 of 1 (latest)

wraith breach
#

I'm trying to calculate the amount of time spent sleeping throughout two periods of time.
There's six spinners - bDay, tDay, tMonth, bMonth, tYear, bYear.
Each day is 8hours, and it takes the time between the birth date and current date provided.

private void calculateActionPerformed(java.awt.event.ActionEvent evt){
    int year = 365;
    // for day in year, sleep += 8. 30 days per month.
    // bDay.getValue() can't be converted to int?
    javax.swing.JOptionPane.showMessageDialog(null, "You have slept approximately: \n Days\n Months \n Years", "SleepCalculator", 1);
}

I'm struggling to figure out how to calculate the time between and I don't know how to convert the values to integers

cosmic heathBOT
#

This post has been reserved for your question.

Hey @wraith breach! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

upbeat forge
#

./run java

import java.time.*;
LocalDate dob = LocalDate.of(1985,1,1);
LocalDate now = LocalDate.now();
Duration between = Duration.between(dob.atStartOfDay(), now.atStartOfDay());
System.out.println(between.toDays());
next anchorBOT
#

Here is your java(15.0.2) output @upbeat forge

13917
upbeat forge
#

Consider using the date API as above. I'll let you work out the rest 👍

wraith breach
#
private void calculateActionPerformed(ActionEvent event){
    LocalDate dob = LocalDate.of((Integer)bYear.getValue(), Month.of((Integer)bMonth.getValue()), (Integer)bDay.getValue());
    LocalDate date = LocalDate.of((Integer)tYear.getValue(), Month.of((Integer)tMonth.getValue()), (Integer)tDay.getValue());

    Duration between = Duration.between(dob.atStartOfDay(), date.atStartOfDay());
    int hours = between.toHoursPart();
    int days = 0;
    int months = 1;
    int years = 2;

    JOptionPane.showMessageDialog(null, String.format("You have slept approximately: \n%s Hours\n%s Days\n%s Months \n%s Years", hours, days, months, years), "SleepCalculator", 1);
}

@upbeat forge the hours always = 0

rare saddle
#

why %s for integers?

#

toHoursPart gets just the hours from midnight, not the total hours

#

since both dates are at midnight, that's always 0

#

use toHours

wraith breach
#

thanks

wraith breach
#

since it needs to be divisible

#

ig toIntExact exisst

rare saddle
wraith breach
#

oh LMAO i didnt think abt that wtf

rare saddle
#

long to int is in the simplest case just (int)longValue

wraith breach
#

ah i was just dumb

#

ive used other oop languages, but new to java

#

so the variable declaration was int hence the mistake💀💀

#

ty

rare saddle
#

yeah you can just use longs for all of it really, much simpler

wraith breach
#

Great, thanks mate