Interacting with time in Java - java

How can I add/subtract with time in Java? For example, I'm writing a program that when you input your bedtime, it then adds 90 minutes (the length of 1 sleep cycle) to tell you the ideal wake up time.
Scanner input;
input = new Scanner (System.in);
int wakeup0;
int wakeup1;
int wakeup2;
int wakeup3;
int wakeup4;
int wakeup5;
System.out.println("When will you be going to bed?");
int gotobed = Integer.parseInt(input.nextLine());
wakeup0 = gotobed + 90;
wakeup1 = wakeup0 + 90;
wakeup2 = wakeup1 + 90;
wakeup3 = wakeup2 + 90;
wakeup4 = wakeup3 + 90;
wakeup5 = wakeup4 + 90;
System.out.println("You should set your alarm for: "+wakeup0+" "+wakeup1+" "+wakeup2+" "+wakeup3+" "+wakeup4+" or "+wakeup5);
How do I make it so that when I add 90 to 915 it gives me 1045 rather than 1095?

Calculate everything in milliseconds. That might at first seem inconvenient but the math is quite straightforward.
When inputting the bedtime, you need to decide how the user will do this. Will it be hours and minutes. Will there be AM/PM or 24 hour clock. And what time zone will you be considering. All of this is done with a Calendar or DateFormat class and it will give you a single long value with the specified time in it.
After that, adding a time offset is easy.
SimpleDateFormat df = new SimpleDateFormat("HHmm");
long bedttime = df.parse(inputValue).getTime();
long wakeup1 = bedttime + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup2 = wakeup1 + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup3 = wakeup2 + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup4 = wakeup3 + (90 * 60 * 1000); //90 minutes in milliseconds.
long wakeup5 = wakeup4 + (90 * 60 * 1000); //90 minutes in milliseconds.
System.out.println("The first wakeup time is "+df.format(new Date(wakeup1)));
Each long value holds the time that the alarm should go off. Use the formatter again to generate a user friendly representation of that time value.

Firstly, there is no direct conversion from a 4 digit number to a time.
So you will need to use Calendar
From this you can get the current date/time Calendar rightNow = Calendar.getInstance();
Then you can use the add method to add your 90 minutes see http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add(int, int)

May not be the exact reply to your question. You should probably use Calendar and SimpleDateFormat in this case like below.
SimpleDateFormat df = new SimpleDateFormat("HHmm");
System.out.println("When will you be going to bed?");
String gotobed = input.nextLine();
Date date = df.parse(gotobed);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, 90);
String wakeup0 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup1 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup2 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup3 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup4 = df.format(calendar.getTime());
calendar.add(Calendar.MINUTE, 90);
String wakeup5 = df.format(calendar.getTime());
System.out.println("You should set your alarm for: " + wakeup0 + " "
+ wakeup1 + " " + wakeup2 + " " + wakeup3 + " " + wakeup4
+ " or " + wakeup5);
For Input 0900 the output will be,
When will you be going to bed?
0900
You should set your alarm for: 1030 1200 1330 1500 1630 or 1800

This will be easier if you separate the hours and minutes given that an hour is made up of 60 and not 100 minutes. Ask the user to input their time as "HH:MM" and parse it using split(":") to get the hours and minutes separately:
System.out.println("When will you be going to bed?");
String rawBedtime = input.nextLine();
String[] gotobed = rawBedtime.split(":");
int minutes = Integer.parseInt(gotobed[0]);
int hours = Integer.parseInt(gotobed[1]);
To get the number of hours and minutes to add:
int additionalHours = 90/60;
int additionalMinutes = 90%60;
However, I would probably Java's Calendar or Date classes. They will take care of a lot of the nitty-gritty for you.

Related

How do I format a double into a time with a print statement in Java?

I'm trying to format a double into a time in Java.
Here is my current code:
int food_intake = 1000;
int calories_burned_per_hour = 173
double hours = food_intake / calories_burned_per_hour;
System.out.println("It will take you " + hours + " hours to burn that food off");
Here is the current output:
It will take you 5.78034682 hours to burn that food off
Here is the desired output:
It will take you 5 hours and 46 minutes to burn that food off
Any help is much appreciated - thank you in advance!
You have to calculate the min part separately as below -
int food_intake = 1000;
int calories_burned_per_hour = 173;
double hours = food_intake / (calories_burned_per_hour * 1.0);
int hrPart = (int) hours;
int minPart = (int) ((hours - hrPart) * 60);
System.out.println("It will take you " + hrPart + " hours and " + minPart + " min to burn that food off");
Duration
The java.time.Duration class represents a span of time unattached to the timeline on the scale of hours, minutes, seconds, and nanos.
Duration works only with integer numbers, not fractional. So multiply your double to the granularity you desire: minutes, seconds, or nanos.
double hours = 5.78034682d ;
double minutes = ( hours * 60d ) ;
Duration d = Duration.ofMinutes( minutes ) ;
String output = d.toString() ; // Standard ISO 8601 format.
String h = d.toHoursPart() ;
String m = d.toMinutesPart() ;
Now ready to assemble your final string.

How to find out if SimpleDateFormat is using seconds or minutes [duplicate]

This question already has answers here:
How to convert milliseconds into human readable form?
(22 answers)
Closed 7 years ago.
I'm making a game with a timer and it tell's you how long you took to complete the game at the end, it's a basic game so some people may beat it in less than a minute so i want to know is there any way to detect if there if the minutes are equal to 00 so then i can set the text to say 00:12 seconds and if it's not equal to 00 then it will say 01:12 Minutes. This is the code that i am using to work out the times.
Date start = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
And the work out the final time is simply
Date now = new Date();
sdf.format(new Date(now.getTime() - start.getTime()))
Fixed it.
Date start = new Date();
SimpleDateFormat sdfm = new SimpleDateFormat("mm");
SimpleDateFormat sdfs = new SimpleDateFormat("ss");
Date now = new Date();
if(sdfm.format(new Date(now.getTime() - start.getTime())).equals("00")){
JOptionPane.showMessageDialog(null, "You Won!! It only took you " + sdfs.format(new Date(now.getTime() - start.getTime())) + " Seconds", "You Won!!", 1);
}else{
JOptionPane.showMessageDialog(null, "You Won!! It only took you " + sdfm.format(new Date(now.getTime() - start.getTime())) + ":" + sdfs.format(new Date(now.getTime() - start.getTime())) + " Minutes", "You Won!!", 1);
System.exit(0);
long start = System.currentTimeMillis();
/*
* Your code
*/
long diff = System.currentTimeMillis() - start;
long seconds = (diff / 1000) % 60;
long minutes = (diff / (1000 * 60)) % 60;
long hours = (diff / (1000 * 60 * 60)) % 24;
System.out.println("Total " + hours + " hours " + minutes + " minutes " + seconds + " seconds");
Refer below links for another possible solutions,
Java-How to calculate accurate time difference while using Joda Time Jar
How can I calculate a time span in Java and format the output?

system Time is showing but with the difference of 1 hour

time is not showing perfectly, I am trying to show my system timings.
Also I am not able to set these
int minut = calendar.getTime().getMinutes();
int hours = calendar.getTime().getHours();
int sec = calendar.getTime().getSeconds();
It gave error:
The method getSeconds() from the type Date is depreciated.
The method getHours() from the type Date is depreciated.
The method getMinutes() from the type Date is depreciated.
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
int hours = cal.getTime();
int minut = cal.getTime();
hours = hours * 30 + minut / 2;
minut = minut * 6;
int sec = cal.getTime();
minut = minut +sec/10;
sec = sec * 6;
hr.setRotate(hours);
minute.setRotate(minut);
second.setRotate(sec);
Scene sc = new Scene(pane);
ps.setScene(sc);
It give me the time for example if my system time is 10:25 it shows 09:25
Your code makes not much sense to me but get keep in mind that Calender.getTimeInMillis() or Date.getTime() return the time in UTC - regardless the timezone you set on the calendar.
Please try below code, it will give you correct time:
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
System.out.println(hour + ":" + minute + ":" + second + ":" + millis);

JAVA convert minutes into default time [hh:mm:ss]

what is the easiest and fastest way to convert minutes (double) to default time hh:mm:ss
for example I used this code in python and it's working
time = timedelta(minutes=250.0)
print time
result:
4:10:00
is there a java library or a simple code can do it?
EDIT: To show the seconds as SS you can make an easy custom formatter variable to pass to the String.format() method
EDIT: Added logic to add one minute and recalculate seconds if the initial double value has the number value after the decimal separator greater than 59.
EDIT: Noticed loss of precision when doing math on the double (joy of working with doubles!) seconds, so every now and again it would not be the correct value. Changed code to properly calculate and round it. Also added logic to treat cases when minutes and hour overflow because of cascading from seconds.
Try this (no external libraries needed)
public static void main(String[] args) {
final double t = 1304.00d;
if (t > 1440.00d) //possible loss of precision again
return;
int hours = (int)t / 60;
int minutes = (int)t % 60;
BigDecimal secondsPrecision = new BigDecimal((t - Math.floor(t)) * 100).setScale(2, RoundingMode.HALF_UP);
int seconds = secondsPrecision.intValue();
boolean nextDay = false;
if (seconds > 59) {
minutes++; //increment minutes by one
seconds = seconds - 60; //recalculate seconds
}
if (minutes > 59) {
hours++;
minutes = minutes - 60;
}
//next day
if (hours > 23) {
hours = hours - 24;
nextDay = true;
}
//if seconds >=10 use the same format as before else pad one zero before the seconds
final String myFormat = seconds >= 10 ? "%d:%02d:%d" : "%d:%02d:0%d";
final String time = String.format(myFormat, hours, minutes, seconds);
System.out.print(time);
System.out.println(" " + (nextDay ? "The next day" : "Current day"));
}
Of course this can go on and on, expanding on this algorithm to generalize it. So far it will work until the next day but no further, so we could limit the initial double to that value.
if (t > 1440.00d)
return;
Using Joda you can do something like:
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
final Period a = Period.seconds(25635);
final PeriodFormatter hoursMinutes = new PeriodFormatterBuilder().appendHours().appendSuffix(" hour", " hours")
.appendSeparator(" and ").appendMinutes().appendSuffix(" minute", " minutes").appendSeparator(" and ")
.appendSeconds().appendSuffix(" second", " seconds").toFormatter();
System.out.println(hoursMinutes.print(a.normalizedStandard()));
//Accept minutes from user and return time in HH:MM:SS format
private String convertTime(long time)
{
String finalTime = "";
long hour = (time%(24*60)) / 60;
long minutes = (time%(24*60)) % 60;
long seconds = time / (24*3600);
finalTime = String.format("%02d:%02d:%02d",
TimeUnit.HOURS.toHours(hour) ,
TimeUnit.MINUTES.toMinutes(minutes),
TimeUnit.SECONDS.toSeconds(seconds));
return finalTime;
}

Add two String Times in java [duplicate]

This question already has answers here:
Sum two dates in Java
(9 answers)
Closed 8 years ago.
I have two String times
1:30:00
1:35:00
Is there a simple way to add these two times and get a new time which should be something
3:05:00?
I want to do this at client side , so if i can avoid any date liabraries
String time1="0:01:30";
String time2="0:01:35";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date1 = timeFormat.parse(time1);
Date date2 = timeFormat.parse(time2);
long sum = date1.getTime() + date2.getTime();
String date3 = timeFormat.format(new Date(sum));
System.out.println("The sum is "+date3);
Ouput : The sum is 00:03:05
Keep in mind that you can convert int values for hours/minutes/seconds to a single int like this:
int totalSeconds = ((hours * 60) + minutes) * 60 + seconds;
And convert back:
int hours = totalSeconds / 3600; // Be sure to use integer arithmetic
int minutes = ((totalSeconds) / 60) % 60;
int seconds = totalSeconds % 60;
Or you can do arithmetic piecemeal as follows:
int totalHours = hours1 + hours2;
int totalMinutes = minutes1 + minutes2;
int totalSeconds = seconds1 + seconds2;
if (totalSeconds >= 60) {
totalMinutes ++;
totalSeconds = totalSeconds % 60;
}
if (totalMinutes >= 60) {
totalHours ++;
totalMinutes = totalMinutes % 60;
}
Use SimpleDateFormat to parse the Strings then you can add the hours minutes and seconds
something like
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
d1 = df.parse("1:30:00");
d2 = df.parse("1:35:00");
Long sumtime= d1.getTime()+d2.getTime();
you can see this here as well it looks like possible duplicate of #####
or if you want to use Calender API, then you can also do it using Calender API, then u can do something like
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
Calendar cTotal = Calendar.getInstance();
cTotal.add(c1.get(Calendar.YEAR), c2.get(Calendar.YEAR));
cTotal.add(c1.get(Calendar.MONTH) + 1)), c2.get(Calendar.MONTH) + 1)); // Months are zero-based!
cTotal.add(c1.get(Calendar.DATE), c2.get(Calendar.DATE));
Just sum them as you sum numbers in 1st-2nd grades, going backwards through them.
Also make sure you move over digits to higher register when needed (i.e. not
always when reaching 10 but when reaching 24 or 60 for hours/minutes).
So I suggest you code this algorithm yourself.

Categories