I am trying to right a program for my introduction to java course. The user enters their birthdate in the following format(19900506), the amount of days the person is then displayed. The program uses the GregorianCalendar class to get today's date and compares the two. Leap years are taken into account. I was able to right the program, but I need to write another version that calculates the difference using my own algorithm. I have hit a wall and can't figure out how to do this. I was thinking of converting the difference between the two dates to milliseconds and then converting to days again. But there is a lot of things to be considerd, like days in months, days remaining from todays date, etc. Any help would be appreciated.
Here is my code:
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class DayssinceBirthV5 {
public static void main(String[] args) {
GregorianCalendar greg = new GregorianCalendar();
int year = greg.get(Calendar.YEAR);
int month = greg.get(Calendar.MONTH);
int day = greg.get(Calendar.DAY_OF_MONTH);
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your birthday: AAAAMMDD): ");
int birthday = keyboard.nextInt();//
int testyear = birthday / 10000;// year
int testmonth = (birthday / 100) % 100;// Month
int testday = birthday % 100;// Day
int counter = calculateLeapYears(year, testyear);
GregorianCalendar userInputBd = new GregorianCalendar(testyear, testmonth - 1, testday);// Input
long diffSec = (greg.getTimeInMillis() - userInputBd.getTimeInMillis());// Räkna ut diff
// long diffSec = greg.get(Calendar.YEAR)-birthday;//calc Diff
long total = diffSec / 1000 / 60 / 60 / 24;// calc dif in sec. Sec/min/hours/days
total += counter;
System.out.println("Today you are : " + total + " days old");
}
private static int calculateLeapYears(int year, int testyear) {
int counter = 0;
for (int i = testyear; i < year; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
counter++;
System.out.println("Amount of leap years: " + counter);
}
}
return counter;
}
}
You can calculate the number of days like this -
Write a method that finds the number of days in a year: Leap years have 366 days, non-leap years have 365.
Write another method that gets a date and finds the day of year - January 1st is day 1, January 2nd is day 2 and so on. You'll have to use the function from 1.
Calculate the following:
Number of days until year's end from date of birth.
Number of days from year's begining until current date.
Numer of days of all years between.
Sum up all of the above.
def daysBetweenDates(self, date1: str, date2: str) -> int:
y1, m1, d1 = map(int, date1.split('-'))
y2, m2, d2 = map(int, date2.split('-'))
m1 = (m1 + 9) % 12
y1 = y1 - m1 // 10
x1= 365*y1 + y1//4 - y1//100 + y1//400 + (m1*306 + 5)//10 + ( d1 - 1 )
m2 = (m2 + 9) % 12
y2 = y2 - m2 // 10
x2= 365*y2 + y2//4 - y2//100 + y2//400 + (m2*306 + 5)//10 + ( d2 - 1 )
return abs(x2 - x1)
Related
I've been trying to convert a float number to years, months, weeks, days, hours, minutes and seconds but I'm not getting it.
For example, if the user enters 768.96 the total would be 2 years, 1 month, 1 week, 1 day, 23 hours, 0 minutes and 2 seconds.
This is what I have.
import javax.swing.JOptionPane;
public class timePartition {
public static void main(String[] args) {
float totalTime;
float userInput;
int years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0;
do{
userInput = Float.parseFloat(JOptionPane.showInputDialog("Enter a positive number to decompose"));
totalTime = userInput;
years = (int) userInput / 365;
userInput = userInput % 10;
months = (int) userInput / 12;
userInput = userInput % 10;
weeks = (int) userInput / 4;
userInput = userInput % 10;
days = (int) userInput / 30;
userInput = userInput % 10;
hours = (int) userInput / 24;
userInput = userInput % 10;
minutes = (int) userInput / 60;
userInput = userInput % 10;
seconds = (int) userInput / 60;
userInput = userInput % 10;
}while (userInput >=1);
System.out.print("The number " +totalTime+ " is " +years+ " years, " +months+ " months, " +weeks+ " weeks, " +days+ " days, " +hours+ " hours, " +minutes+ " minutes, " +seconds+ " seconds.");
}
I don't think you can use modulo 10 to reduce the input after you pull out each of the denominations. Also, you don't need a while loop at all for this.
You have to do something like
years = (int) (userInput / 365);
userInput = userInput - years*365;
and so on. Also, since the input is in days, you have to keep thinking in days when you divide out, so dividing by 12 to get the number of months doesn't make sense. You would instead divide by 30, 31 or 28. Similarly for hours, you would have to multiply the remaining fraction of days by 24, and then take the fractional part of the hours and decompose it similarly into minutes and seconds.
Ok, several things here:
just to make sure you're aware: date/time arithmetic is not as simple as it may seem. Several fields are not uniform in duration, including years (due to leap years in some years but not others), months (28-31 days depending on the month), and even minutes (due to rare but strictly necessary leap seconds). This means that technically you can't properly decompose a total duration count (e.g. "x days") into duration fields, and vice-versa (at least not without some "anchoring" date/time point).
if you want to make incorrect assumptions like "all years have exactly 365 days" and "all months have exactly 30 days" and "all minutes have exactly 60 seconds" then this can be done.
I'm not sure whether you wanted your program to take and decompose a single value, in which case the loop is not necessary, or multiple values, in which case the final print statement should be inside the loop. I've assumed the latter.
based on your example input and the start of your decomposition code, it appears that you want the integral part of the input float value to represent a number of days, with the fractional part representing a time value as a fraction of one day. Your decomposition code is incorrect according to this interpretation; you first must separate the ipart and fpart to decompose independently, and in each step of the decomposition, you must take the remainder on the previous field duration size (e.g. 7 days for a week, 3600 seconds for an hour), rather than a fixed value of 10 (not sure where that came from...) to prepare for the next step of the decomposition. This can be done with the mod-assign operator %=.
Here's working code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TimePartition {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Enter a positive number to decompose");
String input = br.readLine();
if (input.equals("")) break;
float inputAsFloat = Float.parseFloat(input);
if (inputAsFloat == 0.0) break;
// the input is an integral day count, with a possible fractional part representing time as a fraction of one day
int totalDays = (int)inputAsFloat;
int totalSeconds = (int)((inputAsFloat-totalDays)*60.0*60.0*24.0);
// decompose totalDays into date fields
int years = 0;
int months = 0;
int weeks = 0;
int days = 0;
// ignores leap years
years = (int)totalDays/365;
totalDays %= 365;
// assumes all months have 30 days
months = (int)totalDays/30;
totalDays %= 30;
weeks = (int)totalDays/7;
totalDays %= 7;
days = (int)totalDays;
// decompose totalSeconds into time fields
int hours = 0;
int minutes = 0;
int seconds = 0;
hours = (int)totalSeconds/3600;
totalSeconds %= 3600;
// ignores leap seconds
minutes = (int)totalSeconds/60;
totalSeconds %= 60;
seconds = (int)totalSeconds;
System.out.println("The number "+inputAsFloat+" is "+years+" years, "+months+" months, "+weeks+" weeks, "+days+" days, "+hours+" hours, "+minutes+" minutes, "+seconds+" seconds.");
} // end while
} // end main()
} // end class TimePartition
Demo:
bash> ls
TimePartition.java
bash> javac TimePartition.java
bash> ls
TimePartition.class* TimePartition.java
bash> CLASSPATH=. java TimePartition
Enter a positive number to decompose
768.96
The number 768.96 is 2 years, 1 months, 1 weeks, 1 days, 23 hours, 2 minutes, 25 seconds.
I suppose the input is in day.
There are few strange thing in your code :
the while loop is not necessary
(int) userInput will cast userInput in int before the division, not really important here, but be careful ;)
userInput % 10 everywhere
divide by 12 to get the number of month, by 4 to get the number of weeks, and so on
Here is a skeleton of the solution:
float userInput /* = ... */ ;
int years = (int)(userInput/365) ;
userInput = userInput - years*365 ; // or userInput%365 ;
int month = (int)(userInput/30);
userInput = userInput - month*30 ; // or userInput%30 ;
int day = (int) userInput ;
userInput = userInput - day ;
userInput = userInput * 24 ; //transform in hours
int hours = (int)hours ;
userInput = userInput - hours ;
userInput = userInput * 60 ; // transform in minute
int minutes = (int)userInput ;
userInput = userInput - minutes ;
userInput = userInput * 60 ; // transform in second
int seconds = (int) userInput ;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I will start with an example: time is 20:00 (2000) and I want to find how many minutes its been since 09:00 (0900), I tried using mod of 60 but this gave me an off time.
Example:
Elapsed time between 1610 1700
1700-1610 = 90, this is obviously wrong
(1700-1610)%60 = 30,
90-30 equals 60, but the answer should be 50. I'm very confused with what I should be doing, how would I go about dealing with this in java? Thanks!
Convert hours to minutes.
1700 hours = 17*60 minutes
1610 hours = 16*60 minutes + 10 minutes
to find out the difference, simple subtraction will do the job
17*60 - 16*60 - 10
Update:
Assuming user enters in 0000 (hhmm) format, you can simply split by size
//psuedo code
String data = userInput;
int hours = Integer.parseInt(data.split(0,2));
int mins = Intger.parseInt(data.split(2,4));
You mixing two representations of the time
13:50
1350 (minutes)
13:50 is 13 hours and 50 minutes, but 1350 is 1350/60 = 22 hours and 1350%60 = 30 minutes
Before you can add, subtract, multiply or divide time you have to convert it to number. In your case:
Elapsed time between 16:10 17:00
16:10 = 16*60+10 = 970
17:00 = 17*60+00 = 1020
17:00 - 16:10 = 1020 - 970 = 50
In Java you could write:
public int minutesFromTime(String time) {
String [] parts = time.split(":");
int hours = Integer.parseInt(parts[0]);
int minutes = Integer.parseInt(parts[1]);
return hours * 60 + minutes;
}
Then
System.out.println("Difference is "
+ (minutesFromTime("17:00") - minutesFromTime("16:10"))
+ " minutes");
To convert your 24-hour time to minutes you need to determine hours and minutes:
int hours = time / 100;
int minutes = time % 100;
And then calculate minutes since midnight:
int minutesSinceMidnight = (hours * 60) + minutes;
You can subtract the minutesSinceMidnight for both times to arrive at the time difference in minutes.
This simple example should do the job:
public static void main(String[] args) {
String after = "2000";
String before = "0900";
int hours = (parseInt(after) - parseInt(before)) / 100;
int minutes = (parseInt(after) % 100) - (parseInt(before) % 100) % 60;
if (minutes < 0) minutes += 60;
System.out.printf("Minutes passed from %s to %s are %d\n", before, after, hours * 60 + minutes);
}
you are dealing with time (60 min), so you can't directly use the math functions (10 base).
So I suggest that you convert your data to Date and then deal with it.
DateFormat dateFormat = new SimpleDateFormat( "HHmm");
Date date = dateFormat.parse("1610");
Date date2 = dateFormat.parse("1700");
long diff = date2.getTime() - date.getTime();
long diffMinutes = diff / (60 * 1000);
You can't do it like this, you are confusing hour and minute as the same unit in your way to do this.
You should separate hour and minute to get the good answer
for example:
String time1 = "1700";
int hour1 = Integer.parseInt(time1.substring(0,2));
int minute1 = Integer.parseInt(time1.substring(2,4));
From int to String to parse
int timeInt = 1715;
String time1 = ""+timeInt;
int hour1 = Integer.parseInt(time1.substring(0,2));
int minute1 = Integer.parseInt(time1.substring(2,4));
Or staying in int
int timeInt = 1715;
int hour = timeInt / 100;
int min = timeInt - hour*100;
If we assume user will always input in XXXX (hhmm) format you can try using this code:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter first time value: ");
int firstTime = userInput.nextInt();
System.out.print("Enter second time value: ");
int secondTime = userInput.nextInt();
int hoursFirst = (int)(firstTime/100);
int minutesFirst = firstTime%100;
int hoursSecond = (int)(secondTime/100);
int minutesSecond = secondTime%100;
int difference = Math.abs((hoursSecond - hoursFirst - 1) * 60 + (60 - minutesFirst) + minutesSecond);
System.out.println("Difference between " + hoursFirst + ":" + minutesFirst
+ " and " + hoursSecond + ":" + minutesSecond + " is " + difference + " minutes.");
}
Output example:
Enter first time value: 1820
Enter second time value: 1610
Difference between 18:20 and 16:10 is 130 minutes.
So for an assignment we had to write a program that takes two times in military time and shows the difference in hours and minutes between them assuming the first time is the earlier of the two times. We weren't allowed to use if statements as it technically has not be learned. Here's an example of what it'd look like run. In quotes I'll put what is manually entered when it is prompted to.
java MilitaryTime
Please enter first time: "0900"
Please enter second time: "1730"
8 hours 30 minutes (this is the final answer)
I was able to quite easily get this part done with the following code:
class MilitaryTime {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the first time: ");
int FirstTime = in.nextInt();
System.out.println("Please enter the second time: ");
int SecondTime = in.nextInt();
int FirstHour = FirstTime / 100;
int FirstMinute = FirstTime % 100;
int SecondHour = SecondTime / 100;
int SecondMinute = SecondTime % 100;
System.out.println( ( SecondHour - FirstHour ) + " hours " + ( SecondMinute
- FirstMinute ) + " minutes " );
}
}
Now my question is something wasn't assigned (or I wouldn't be here!) is there's another part to this question in the book that says to take that program we just wrote and deal with the case where the first time is later than the second. This has really intrigued me about how this would be done and has really stumped me. Again we aren't allowed to use if statements or this would be easy we basically have all the mathematical functions to work with.
An example would be the first time is now 1730 and the second time is 0900 and so now it returns 15 hours 30 minutes.
I would like to suggest to use org.joda.time.DateTime. There are a lot of date and time functions.
Example :
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm");
Date startDate = format.parse("10-05-2013 09:00");
Date endDate = format.parse("11-05-2013 17:30");
DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);
int years = Years.yearsBetween(jdStartDate, jdEndDate).getYears();
int days = Days.daysBetween(jdStartDate, jdEndDate).getDays();
int months = Months.monthsBetween(jdStartDate, jdEndDate).getMonths();
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();
System.out.println(hours + " hours " + minutes + " minutes");
Your expected program will be as below :
SimpleDateFormat format = new SimpleDateFormat("hhmm");
Dates tartDate = format.parse("0900");
Date endDate = format.parse("1730");
DateTime jdStartDate = new DateTime(startDate);
DateTime jdEndDate = new DateTime(endDate);
int hours = Hours.hoursBetween(jdStartDate, jdEndDate).getHours();
int minutes = Minutes.minutesBetween(jdStartDate, jdEndDate).getMinutes();
minutes = minutes % 60;
System.out.println(hours + " hours " + minutes + " minutes");
Output :
8 hours 30 minutes
Normally, when dealing with time calculations of this nature I would use Joda-Time, but assuming that you don't care about the date component and aren't rolling over the day boundaries, you could simply convert the value to minutes or seconds since midnight...
Basically the problem you have is the simple fact that there are 60 minutes in an hour, this makes doing simple mathematics impossible, you need something which is more common
For example, 0130 is actually 90 minutes since midnight, 1730 is 1050 minutes since midnight, which makes it 16 hours in difference. You can simply subtract the two values to get the difference, then convert that back to hours and minutes...for example...
public class MilTimeDif {
public static void main(String[] args) {
int startTime = 130;
int endTime = 1730;
int startMinutes = minutesSinceMidnight(startTime);
int endMinutes = minutesSinceMidnight(endTime);
System.out.println(startTime + " (" + startMinutes + ")");
System.out.println(endTime + " (" + endMinutes + ")");
int dif = endMinutes - startMinutes;
int hour = dif / 60;
int min = dif % 60;
System.out.println(hour + ":" + min);
}
public static int minutesSinceMidnight(int milTime) {
double time = milTime / 100d;
int hours = (int) Math.floor(time);
int minutes = milTime % 100;
System.out.println(hours + ":" + minutes);
return (hours * 60) + minutes;
}
}
Once you start including the date component or rolling over day boundaries, get Joda-Time out
I would do something like:
System.out.println(Math.abs( SecondHour - FirstHour ) + " hours " + Math.abs( SecondMinute - FirstMinute ) + " minutes " );
The absolute value will give you the difference between the two times as a positive integer.
You could do something like this
//Code like you already have
System.out.println("Please enter the first time: ");
int firstTime = in.nextInt();
System.out.println("Please enter the second time: ");
int secondTime = in.nextInt();
//Now we can continue using the code you already wrote by
//forcing the smaller of the two times into the 'firstTime' variable.
//This forces the problem to be the same situation as you had to start with
if (secondTime < firstTime) {
int temp = firstTime;
firstTime = secondTime;
secondTime = temp;
}
//Continue what you already wrote
There are many other ways but this was something I used for similar problems while learning. Also, note that I changed variable names to follow java naming conventions - variables are lowerCamelCase.
I used 3 classes. Lets go over theory first.
We have two times: A and B.
if AtimeDiff = (B-A).....which can be written -(A-B)
if A>B, then timeDiff = 1440- (A-B) [1440 is total minutes in day]
Thus we need to make timeDiff = 1440 - (A-B) and we need to make 1440 term dissapear when A
Lets make a term X = (A-B+1440) / 1440 (notice "/" is integer division.
'if A
'if A>B then X = 1;
Now look at a new term Y = 1440 * X.
'if A
'if A>B then Y = 1440'.
PROBLEM SOLVED. Now just plug into Java Programs. Note what happens if A=B. Our program will assume we know no time passes if times are exact same time. It assumes that 24 hours have passed. Anyways check out the 3 programs listed below:
Class #1
public class MilitaryTime {
/**
* MilitaryTime A time has a certain number of minutes passed at
* certain time of day.
* #param milTime The time in military format
*/
public MilitaryTime(String milTime){
int hours = Integer.parseInt(milTime.substring(0,2));
int minutes = Integer.parseInt(milTime.substring(2,4));
timeTotalMinutes = hours * 60 + minutes;
}
/**
* Gets total minutes of a Military Time
* #return gets total minutes in day at certain time
*/
public int getMinutes(){
return timeTotalMinutes;
}
private int timeTotalMinutes;
}
Class#2
public class TimeInterval {
/**
A Time Interval is amount of time that has passed between two times
#param timeA first time
#param timeB second time
*/
public TimeInterval(MilitaryTime timeA, MilitaryTime timeB){
// A will be shorthand for timeA and B for timeB
// Notice if A<B timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B)
// Notice if A>B timeDifferential = - (A - B)
// Both will use timeDifferential = TOTAL_MINUTES_IN_DAY - (A - B),
// but we need to make TOTAL_MINUTES_IN_DAY dissapear when needed
//Notice A<B following term "x" is 1 and if A>B then it is 0.
int x = (timeA.getMinutes()-timeB.getMinutes()+TOTAL_MINUTES_IN_DAY)
/TOTAL_MINUTES_IN_DAY;
// Notice if A<B then term "y" is TOTAL_MINUTES_IN_DAY(1440 min)
// and if A<B it is 0
int y = TOTAL_MINUTES_IN_DAY * x;
//yay our TOTAL_MINUTES_IN_DAY dissapears when needed.
int timeDifferential = y - (timeA.getMinutes() - timeB.getMinutes());
hours = timeDifferential / 60;
minutes = timeDifferential % 60;
//Notice that if both hours are equal, 24 hours will be shown.
// I assumed that we would knoe if something start at same time it
// would be "0" hours passed
}
/**
* Gets hours passed between 2 times
* #return hours of time difference
*/
public int getHours(){
return hours;
}
/**
* Gets minutes passed after hours accounted for
* #return minutes remainder left after hours accounted for
*/
public int getMinutes(){
return minutes;
}
private int hours;
private int minutes;
public static final int TOTAL_MINUTES_IN_DAY = 1440;//60minutes in 24 hours
}
Class#3
import java.util.Scanner;
public class MilitaryTimeTester {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter time A: ");
MilitaryTime timeA = new MilitaryTime(in.nextLine());
System.out.println("Enter time B: ");
MilitaryTime timeB = new MilitaryTime(in.nextLine());
TimeInterval intFromA2B = new TimeInterval(timeA,timeB);
System.out.println("Its been "+intFromA2B.getHours()+" hours and "+intFromA2B.getMinutes()+" minutes.");
}
}
import java.util.Scanner;
public class TimeDifference{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// read first time
System.out.println("Please enter the first time: ");
int firstTime = in.nextInt();
// read second time
System.out.println("Please enter the second time: ");
int secondTime = in.nextInt();
in.close();
// if first time is more than second time, then the second time is in
// the next day ( + 24 hours)
if (firstTime > secondTime)
secondTime += 2400;
// first hour & first minutes
int firstHour = firstTime / 100;
int firstMinute = firstTime % 100;
// second hour & second minutes
int secondHour = secondTime / 100;
int secondMinute = secondTime % 100;
// time difference
int hourDiff = secondHour - firstHour;
int minutesDiff = secondMinute - firstMinute;
// adjust negative minutes
if (minutesDiff < 0) {
minutesDiff += 60;
hourDiff--;
}
// print out the result
System.out.println(hourDiff + " hours " + minutesDiff + " minutes ");
}
}
This one is done without using ifs and date thingy. you just need to use integer division "/", integer remainder thing"%", and absolute value and celing. might be able to be simplified but im too lazy at moment. I struggled for hours to figure out and seems nobody else got the answer without using more advanced functions. this problem was in Cay Horstmann's Java book. Chapter 4 in Java 5-6 version of the book "Java Concepts"
import java.util.Scanner;
public class MilitaryTime {
public static void main (String[] args){
//creates input object
Scanner in = new Scanner(System.in);
System.out.println("Enter time A: ");
String timeA = in.next();
System.out.println("Enter time B: ");
String timeB = in.next();
//Gets the hours and minutes of timeA
int aHours = Integer.parseInt(timeA.substring(0,2));
int aMinutes = Integer.parseInt(timeA.substring(2,4));
//Gets the hours and minutes of timeB
int bHours = Integer.parseInt(timeB.substring(0,2));
int bMinutes = Integer.parseInt(timeB.substring(2,4));
//calculates total minutes for each time
int aTotalMinutes = aHours * 60 + aMinutes;
int bTotalMinutes = bHours * 60 + bMinutes;
//timeA>timeB: solution = (1440minutes - (aTotalMinutes - bTotalMinutes))
//timeA<timeB: solution is (bTotalMinutes - aTotalMinutes) or
//-(aTotalMinutes - bTotalMinutes)
//we need 1440 term when timea>timeeB... we use mod and mod remainder
//decider is 1 if timeA>timeB and 0 if opposite.
int decider = ((aTotalMinutes - bTotalMinutes +1440)/1440);
// used 4 Special case when times are equal. this way we get 0
// timeDiffference term when equal and 1 otherwise.
int equalsDecider = (int) Math.abs((aTotalMinutes - bTotalMinutes));
//fullDayMaker is used to add the 1440 term when timeA>timeB
int fullDayMaker = 1440 * decider;
int timeDifference = (equalsDecider)* (fullDayMaker - (aTotalMinutes - bTotalMinutes));
// I convert back to hours and minmutes using modulater
System.out.println(timeDifference/60+" hours and "+timeDifference%60+" minutes");
}
}
java.time
Java 8 and later includes the new java.time framework. See the Tutorial.
The new classes include LocalTime for representing a time-only value without date and without time zone.
Another class is Duration, for representing a span of time as a total number of seconds and nanoseconds. A Duration may be viewed as a number of hours and minutes.
By default the Duration class implements the toString method to generate a String representation of the value using the ISO 8601 format of PnYnMnDTnHnMnS where the P marks the beginning and the T separates the date portion from the time portion. The Duration class can parse as well as generate strings in this standard format.
So, the result in example code below is PT8H30M for eight and a half hours. This format is more sensible than 08:30 which can so easily be confused for a time rather than a duration.
String inputStart = "0900";
String inputStop = "1730";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HHmm" );;
LocalTime start = formatter.parse ( inputStart , LocalTime :: from );
LocalTime stop = formatter.parse ( inputStop , LocalTime :: from );
Duration duration = Duration.between ( start , stop );
Dump to console.
System.out.println ( "From start: " + start + " to stop: " + stop + " = " + duration );
When run.
From start: 09:00 to stop: 17:30 = PT8H30M
import java.util.*;
class Time
{
static Scanner in=new Scanner(System.in);
public static void main(String[] args)
{
int time1,time2,totalTime;
System.out.println("Enter the first time in military:");
time1=in.nextInt();
System.out.println("Enter the second time in military:");
time2=in.nextInt();
totalTime=time2-time1;
String temp=Integer.toString(totalTime);
char hour=temp.charAt(0);
String min=temp.substring(1,3);
System.out.println(hour+" hours "+min+" minutes");
}
}
Right now I am finding out 25% of a persons years and for example if you had 5 years 25% is 1.25. Though the plugin im making cant remove 1.25 years from you the .25 needs to be converted to weeks and then any leftovers to days and so on. Though I dont know how I would convert these times.
Integer y = itapi.getPlayerYears(player.getName());
Double yremove = Integer.valueOf(y) * 0.25;
Integer w = itapi.getPlayerWeeks(player.getName());
Double wremove = Integer.valueOf(w) * 0.25;
Integer d = itapi.getPlayerDays(player.getName());
Double dremove = Integer.valueOf(d) * 0.25;
Integer h = itapi.getPlayerHours(player.getName());
Double hremove = Integer.valueOf(h) * 0.25;
Integer m = itapi.getPlayerMinutes(player.getName());
Double mremove = Integer.valueOf(m) * 0.25;
Integer s = itapi.getPlayerSeconds(player.getName());
Double sremove = Integer.valueOf(s) * 0.25;
String yminus = String.valueOf(yremove) + 'y';
String wminus = String.valueOf(wremove) + 'w';
String dminus = String.valueOf(dremove) + 'd';
String hminus = String.valueOf(hremove) + 'h';
String mminus = String.valueOf(mremove) + 'm';
String sminus = String.valueOf(sremove) + 's';
ItemStack book = itapi.createTimeCard("Death of " + player.getName(), yminus + wminus + dminus + hminus + mminus + sminus, 1);
itapi.removeTime(player.getName(), yminus + wminus + dminus + hminus + mminus + sminus );
e.getDrops().add(book);
Would it be possible to work the conversion out or would it be better to convert all time to seconds then take 25% and convert it back?
I would use nested ifs and pass the remainder around. I have not tested this but it should give you an idea.
Integer y = itapi.getPlayerYears(player.getName());
double yremove = Integer.valueOf(y) *0.25;
double numWeeks = yremove * 52; //returns the number in weeks
double numDays =0;
double numHours =0;
double numMinutes =0;
double numSeconds =0;
if(numWeeks % 52 != 0){
numDays = (numWeeks % 52) * 7;
if(numDays % 7 !=0){
numHours = (numDays % 7) * 24;
if(numHours % 24 !=0){
numMinutes = (numHours % 24) * 60;
if(numMinutes % 60 !=0){
numSeconds = (numMinutes % 60) * 60;
}
}
}
}
//... then convert to string as you are already doing and pass it to removeTime()
You can use Calendar class to calculate this for you, something like:
Calendar c = Calendar.getInstance();
double millis = 1.25 * 31557600 * 1000;
long l = (long) millis;
c.setTimeInMillis(l);
System.out.println(c.get(Calendar.YEAR) + " Year");
System.out.println(c.get(Calendar.MONTH) + " months");
System.out.println(c.get(Calendar.WEEK_OF_MONTH) + " weeks");
System.out.println(c.get(Calendar.DAY_OF_MONTH) + " days");
System.out.println(c.get(Calendar.HOUR) + " hours");
System.out.println(c.get(Calendar.MINUTE) + " minutes");
System.out.println(c.get(Calendar.SECOND) + " seconds");
Output:
1971 Year
3 months
1 weeks
2 days
7 hours
0 minutes
0 seconds
Calendar defaults the starting year to 1970, you can further manipulate year and months to weeks if need be.
Create a class to manage time. This class will have methods to return time in terms of years, weeks, months, etc.
public class Time{
private long milliseconds;
public double getSeconds(){
double seconds = milliseconds/1000.0;
return seconds;
}
public void subtractSeconds(double seconds){
long millisInSeconds = (long)(seconds*1000);
this.millisecionds -= millisInSeconds;
}
//write more methods for years, months etc.
}
Then, use this class to retrieve years, months, weeks and subtract the difference. This will keep your code clean, and easy to understand.
Time time = new Time(1000*60*60);
int years = (int)time.getYears();
time.subtractYears(years);
int months = (int)time.getMonths();
time.subtractMonths(months);
I am writing a program for my programming class, where the objective is to calculate the day of the week of a day and month entered. I must do this without using the Calendar class.
My code works with any month/year I supply, except for this month(7/2013). I can't figure out why that would be. Can anybody help with this?
Examples of the outputs are as follows:
Wrong example
run:
Gregorian Calendar Creator
Enter a month: 7
Enter a year: 2013
0=Sun, 1=Mon, 2=Tues, 3=Wed, 4=Thu, 5=Fri, 6=Sat
Test this in a UNIX terminal by typing 'cal July 2013' or similar date
First day of the month: 2
First day of the year: 1
BUILD SUCCESSFUL (total time: 5 seconds)
Right Example
run:
Gregorian Calendar Creator
Enter a month: 7
Enter a year: 2012
0=Sun, 1=Mon, 2=Tues, 3=Wed, 4=Thu, 5=Fri, 6=Sat
Test this in a UNIX terminal by typing 'cal July 2013' or similar date
First day of the month: 1
First day of the year: 0
BUILD SUCCESSFUL (total time: 5 seconds)
I have linked a downloadable Java file here
package calendar;
/**
*
* #author Michael Dornisch
*/
import java.util.Scanner;
public class Calendar {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Initiating vars
int inMonth;
int inYear;
//Initiating Scanner
Scanner input = new Scanner(System.in);
System.out.println("Gregorian Calendar Creator"); //Just a print line
/* This block gets a month. Instead of exiting when the user inputs an
* invalid month, it instead asks again untl a proper month is used.
*/
System.out.print("Enter a month: ");
inMonth = input.nextInt();
while (inMonth > 12 || inMonth <= 0) {
System.out.println("ERROR: Improper month. Please enter a proper numerical month (1-12).");
System.out.print("Enter a month: ");
inMonth = input.nextInt();
}
/* This block gets a year. Instead of exiting when the user inputs an
* invalid year, it instead asks again untl a proper year is used.
*/
System.out.print("Enter a year: ");
inYear = input.nextInt();
while (inYear < 1752) {
System.out.println("ERROR: Improper Year. Please enter a year that is 1753 or greater.");
System.out.print("Enter a year: ");
inYear = input.nextInt();
}
/* Here is where I am testing everything
*
*/
Calendar newCal = new Calendar();
System.out.println("0=Sun, 1=Mon, 2=Tues, 3=Wed, 4=Thu, 5=Fri, 6=Sat");
System.out.println("Test this in a UNIX terminal by typing 'cal July 2013' or similar date");
System.out.println("First day of the month: " + newCal.firstDayOfMonth(inMonth, inYear));
System.out.println("First day of the year: " + newCal.firstDayOfYear(inYear));
}
public boolean leap(int inputYear) {
/* This IF is checked first. If the year is divisible by 100, it isn't a
* leap year unless it is also divisible by 400.
*/
if (inputYear % 100 == 0) {
if (inputYear % 400 == 0) {
return (true);
} else {
return (false);
}
}
//Any other number that's divisible by 4 is also a leap year
if (inputYear % 4 == 0) {
return (true);
} else {
return (false);
}
}
public int firstDayOfYear(int inputYear) {
/*
* Here is a formula for finding the day of the week for ANY date.
* N = d + 2m + [3(m+1)/5] + y + [y/4] - [y/100] + [y/400] + 2
* N = day of week
* d = day of month
* m = number of month
* y = year
* mod 7 for answer
* 0 = sunday, 1 = monday, etc.
*/
int day = 5 + (6 / 5) + inputYear + (inputYear / 4) - (inputYear / 100) + (inputYear / 400);
day = day % 7;
return (day);
}
public int firstDayOfMonth(int inputMonth, int inputYear) {
/*
* Here is a formula for finding the day of the week for ANY date.
* N = d + 2m + [3(m+1)/5] + y + [y/4] - [y/100] + [y/400] + 2
* N = day of week
* d = day of month
* m = number of month
* y = year
* mod 7 for answer
* 0 = sunday, 1 = monday, etc.
*/
int day = 3 + (2 * inputMonth) + ((3 * (inputMonth + 1)) / 5) + inputYear + (inputYear / 4) - (inputYear / 100) + (inputYear / 400);
day = day % 7;
return (day);
}
}
Not sure if you're formula is correct and the numbers to day matches up with it. Link
N = d + 2m + [3(m+1)/5] + y + [y/4] - [y/100] + [y/400] + 2
i would also make this method more generic
public int firstDayOfYear(int day, int month, int year) {
int day = day + (2*month) + ((3*(month+1))/5) + year + (year/4) - (year/100) + (year/ 400) +2;
return day % 7;
}
System.out.println("First day of the year: " + newCal.firstDayOfYear(1, 1, inYear));
The leap method is never called. That could be that. Because the first day of this month is Monday not Tuesday (just a day before => because last year was a leap year)