So I'm writing an app that has similar functionality to an alarm clock. It asks for the user to input a time. But I've been stuck on how to figure this out for a while.
The method needs to find the difference in minutes between the user selected time, and the current time. Assuming that the user will always put in a time that is AFTER the current time (otherwise it wouldn't make sense to use my app), the difference would just be (userTimeInMins - currTimeInMins), where both are calculated by ((hours * 60) + minutes).
BUT. Here's the problem:
Ex 1) If the current time is 10 PM, and the user enters in the time 2 AM. The above algorithm would say that the difference between the two times is (22 * 60 + 0) - (2 * 60 + 0), which is clearly incorrect because this would mean there is a difference of 20 hours between 10PM and 2 AM, when the difference is actually 4 hours.
Ex 2) If the current time is 1PM, and the user enters in the time 2AM. The above algorithm would say that the difference between the two times is (13 * 60 + 0) - (2 * 60 + 0), which is again incorrect because this would mean there is a difference of 11 hours, when the difference is actually 13 hours.
What I have so far
I've realized that for example 1 and for example 2, the difference in minutes can be calculated with
(((24 + userHours) * 60) + userMinutes) - currTimeInMins
I'm struggling to come up with decision statements in the method to determine whether to use the first method or the second method to calculate the difference in minutes.
The Code
// Listener for the time selection
TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String currAM_PM = "";
String userAM_PM = "";
// Get user AM/PM
int hourToShow = 0;
if (hourOfDay > 12){
hourToShow = hourOfDay - 12;
userAM_PM = "PM"
}
else if (hourOfDay == 12){
hourToShow = hourOfDay;
userAM_PM = "PM"
}
else{
hourToShow = hourOfDay;
userAM_PM = "AM"
}
// Update the time field to show the selected time in 12-hr format
EditText timeField = (EditText) findViewById(R.id.editTime);
timeField.setText(hourToShow + ":" + minute + " " + userAM_PM);
// Get current hour
SimpleDateFormat sdf = new SimpleDateFormat("HH");
String cHour = sdf.format(new Date());
int currHour = Integer.parseInt(cHour);
// Get current AM/PM
if (currHour > 12){
currAM_PM = "PM"
}
else if (currHour == 12){
currAM_PM = "PM"
}
else{
currAM_PM = "AM"
}
// Calculate the time to use
// If the selected hour is less than the current hour AND am_pm is "AM"
// THIS IS THE WHERE I NEED HELP
//--------------------------------------------------------------
if(currAM_PM == "PM" && userAM_PM == "AM" .... ??????) {
//take 24, add the hour, use same minute. so that 3 am is 27:00.
timeToUse = ((24 + hourOfDay) * 60) + minute;
}
else
timeToUse = (hourOfDay * 60) + minute;
}
// timeToUse is then passed through an intent extra to the next activity
// where the difference between it and the current time is calculated and used
// for other purposes.
};
Thanks for any help ahead of time.
Solution
I used a DatePickerDialog and a TimePickerDialog to load a Calendar object with the user selected year, month, etc.
Then I created a Date object, initializing it to cal.getDate().
I then loaded Date.getDate() into a long variable, giving the time in miliseconds from Jan 1, 1970.
I then divided this number by 60000 to get the time in minutes.
I did the same thing for the current date, and found the difference in between the two.
Thanks for all help.
Related
IMPORTANT: external libraries, Date and Instant class are not allowed
You may not use any library routines for manipulation of time or
dates, such as converting UNIX time to a date string or for formatting
date strings in general. All calculations for determining year, month,
day, and time must appear in your source.
I wrote this program to convert from UNIX time (time in seconds since 12:00 AM January 1, 1970) to normal date and time. At first glance it seems to work fine, but in some tests it was off by exactly one day. The hours, minutes, months, and years are always correct, but the days are one too few.
For example, when using UNIX time 1234567890 the program produces 11:31 PM 02/13/2009, which is correct! However when inputing 1111111111 (10 1's), the program produces 1:58 AM 03/17/2005, where it should output 01:58 AM 03/18/2005. 64075132196 produces 7:49 AM 06/17/4000 (correct) but 95632040996 produces 7:49 AM 06/16/5000, where it should be the 17th day instead of the 16th.
In order to check my program, I entered a date and time into https://www.unixtimestamp.com/ and entered the resulting UNIX time into my program. (This is how I managed to get exact UNIX codes in the troubleshooting above).
I would appreciate help finding this error and additionally implementing a more efficient solution to this problem altogether.
import java.util.*;
class Main {
public static void main(String[] args) {
System.out.println("\nEnter UNIX time");
Scanner scan = new Scanner(System.in);
int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int[] leapYearMonthDays = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
long unix = scan.nextLong();
int years = 0, months = 0, days = 0, hours = 0, minutes = 0;
boolean leapYear = false;
String AMPM = "AM";
while (unix >= 60) {
unix -= 60;
minutes++;
if (minutes >= 60) {
minutes -= 60;
hours++;
}
if (hours >= 24) {
hours -= 24;
days++;
}
if (leapYear) {
if (days >= leapYearMonthDays[months]) {
days -= leapYearMonthDays[months];
months++;
}
}
else {
if (days >= monthDays[months]) {
days -= monthDays[months];
months++;
}
}
if (months >= 12) {
if (isLeapYear(1970 + years)) leapYear = true; else leapYear = false;
months -= 12;
years++;
}
}
if (hours > 12) {
AMPM = "PM";
hours -= 12;
}
if (days == 0) days = 1;
String daysString = String.valueOf(days);
if (daysString.length() == 1) daysString = "0" + daysString;
String monthsString = String.valueOf(months + 1);
if (monthsString.length() == 1) monthsString = "0" + monthsString;
String minutesString = String.valueOf(minutes);
if (minutesString.length() == 1) minutesString = "0" + minutesString;
if (hours == 0) hours = 12;
System.out.println("\n" + hours + ":" + minutesString + " " + AMPM + " " + monthsString + "/" + daysString + "/" + (years + 1970));
}
public static boolean isLeapYear (int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
return true;
}
else return false;
}
else return true;
}
return false;
}
}
You created your own code. That probably was the intent of the homework.
Now pinpoint the problem.
For that you can actually create a loop generating different Unix time values.
For each of these values calculate the date using your code, in parallel calculate the date using java.util.Date or java.util.Instant. Compare the dates and print results suitable so you can pinpoint the situations where your code produces deviations. Try to understand the deviations and improve your code.
With that you would not only exercise coding date calculations but also automated testing or test driven development.
Given
UNIX time (time in seconds since 12:00 AM January 1, 1970)
Assume if we convert 0 as integer timestmap in unix-epoch format to a java.util.Date we solved it.
Using java.util.Date (prior to Java 8)
long unixTimeInMilliseconds = 0;
Date convertedDate = new java.util.Date(unixTimeInMilliseconds);
System.out.println(convertedDate);
Prints:
Thu Jan 01 00:00:00 GMT 1970
Using java.time.Instant or suitable Java 8 class
You can also use the Java Date/Time API introduced since Java 8 in a similar manner:
long unixTimeInMilliseconds = 0; // 0 ms
Instant timestamp = Instant.ofEpochMilli(unixTimeInMilliseconds);
System.out.println(timestamp);
Prints:
1970-01-01T00:00:00Z
See also
Unix epoch time to Java Date object
I've been stuck on this issue for the past 4 hours trying different strategies which haven't prevailed much at all having checked countless posts on here and Google. Basically what I am trying to do is print out only the business working days within a week mon-fri. I have tried incrementing the day of the year each time the weekend days come up but of course this messes up the order of the days after. For example instead of having:
Iteration: 0, 1, 2, 3, 4, 5, 6, 7, 8....
Day: (0)Friday, (1)Saturday, (2)Sunday, (3)Monday, (4)Tuesday, (5)Wednesday, (6)Thursday, (7)Friday, (8)Saturday....etc
I require:
Day: (0)Friday, (1)Monday, (2)Tuesday (3)Wednesday, (4)Thursday, (5)Friday, (6)Monday, (7)Tuesday, (8)Wednesday....etc
Here's the code:
public static void date(int day) {
now = Calendar.getInstance();
//SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");//version 1
SimpleDateFormat format = new SimpleDateFormat("EEEE d MMMM yyyy"); //version 2
String[] days = new String[maxDayCount]; //limits the number of days to print out(ordinarily h)
now.add(Calendar.DAY_OF_YEAR, day + 1); //Increments from test count + 1 due to count starting at 0 (would be today). Increments the date to get from today.
int DayOfWeek = now.get(Calendar.DAY_OF_WEEK);
boolean WorkingDayCheck = ((DayOfWeek >= Calendar.MONDAY) && (DayOfWeek <= Calendar.FRIDAY));
if(WorkingDayCheck) {
days[day] = format.format(now.getTime());
} else {
//
}
now.add(Calendar.DAY_OF_MONTH, 1);
System.out.println("-----------Day " + day + ": " + String.valueOf(days[day])); //v2: print out each line
}//END OF METHOD: date
The idea is that I have an iteration elsewhere which passes the day number to this method in order for this to use that number to then print out the date. I am now back to what I was with originally before trying a load of things which at the moment with the check I am doing with the WorkingDayCheck boolean the print out is of course returning null when the weekend days come about.
Any ideas chaps?
Thanks for your time.
I think this will solve your problem.
First, why do you define the array days each time you enter the method then you populate only one value in it?
Your String[] days = new String[maxDayCount]; should be a member variable not a local variable. So initialize this array outside this method.
Also initialize another int that represent the last empty location in your array. (defaults to 0)
public class Foo {
int maxDayCount = 365;
String[] days = new String[maxDayCount];
int finalIndex = 0;
public static void date(int day) {
now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("EEEE d MMMM yyyy");
String[] days = new String[maxDayCount]; //limits the number of days to print out(ordinarily h)
now.add(Calendar.DAY_OF_YEAR, day + 1); //Increments from test count + 1 due to count starting at 0 (would be today). Increments the date to get from today.
int DayOfWeek = now.get(Calendar.DAY_OF_WEEK);
boolean WorkingDayCheck = ((DayOfWeek >= Calendar.MONDAY) && (DayOfWeek <= Calendar.FRIDAY));
if(WorkingDayCheck) {
days[finalIndex++] = format.format(now.getTime());
System.out.print("(" + (finalIndex - 1) + ")" + String.valueOf(days[finalIndex - 1]))
} else {
//
}
}
public static void main(String[]args) {
int day = 0;
while(finalIndex != maxDaysCount) {
date(day++);
}
}
}
Now your days array will be populated with working days only in their respective indices. For example in days[0] will be Friday then days[1] will be Saturday and so on since you have a pointer finalIndex that is independent of the value of day that is input to your method from the iteration.
If I get your problem correctly you want to do somewhat like following,
Working Day #1 = 0 Week + 1 Day = 1st Day
..
Working Day #5 = 0 Week + 5 Days = 5th Day
Working Day #6 = 1 Week + 1 Day = 8th Day
..
Working Day #10 = 1 Week + 5 Days = 12th Day
And then print the 1st,2nd,3rd calendar day of the year.
If that is the case you can try finding the calendar day from working day like something,
int div = day/5;
int rem = day%5;
int calendarDay = 0;
if(day>5){
if(rem == 0)
calendarDay = (div-1)*7 + 5;
else
calendarDay = div*7 + rem;
}else
calendarDay = day;
And then find the Calendar day for that date like
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.DAY_OF_YEAR, day);
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.ENGLISH);
formatter.format("%tD", calendar);
System.out.println(sb);
The code is not a solution, but I guess it points to where you want to go.
Having played around with the code I have achieved what I was after now with:
public static String getDate4(int day) {
now = Calendar.getInstance();
//SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");//version 1
SimpleDateFormat format = new SimpleDateFormat("EEEE d MMMM yyyy"); //version 2
now.add(Calendar.DAY_OF_YEAR, day + 1); //Increments from test count + 1 due to count starting at 0 (would be today). Increments the date to get from today.
int DayOfWeek = now.get(Calendar.DAY_OF_WEEK);
boolean WorkingDayCheck = ((DayOfWeek >= Calendar.MONDAY) && (DayOfWeek <= Calendar.FRIDAY));
if(WorkingDayCheck) {
days[finalIndex++] = format.format(now.getTime());
return "\n(" + (finalIndex - 1) + ") " + String.valueOf(days[finalIndex - 1]);
} else {
now.add(Calendar.DATE, 2); //advance dates by two
dayCount = dayCount + 2; //Increase the day count by 2 to ensure that later dates are also incremented to avoid duplication i.e. Monday(Sat), Tuesday(Sun), Monday, Tuesday, Wed...
days[finalIndex++] = format.format(now.getTime());
return "\n(" + (finalIndex - 1) + ") " + String.valueOf(days[finalIndex - 1]);
}//END OF if else
}//END OF getDate4 method
I had to add and use an external dayCount (similar to the day int #Mohammed Osama used) separate from the count used in the mains methods iteration which I used previously to feed into this method and then when a weekend came up I incremented the date by 2 which is something I had experimented with before however the problem came when the weekend ended and it was back onto non weekend dates which ended up with:
Friday
Monday (previously Saturday)
Tuesday (previously Sunday)
Monday (weekend over, now back onto Monday) <--- Issue here and onwards
Tuesday
This is where the new dayCount came in which is now fed into this method simply as:
//Main method
//Iteration code start
getDate4(dayCount++);
//Iteration end
Incrementing this by 2 each time a weekend was encountered pushed the later dates to their appropriate position therefore now I am getting what I was always after being:
Friday
Monday (previously Saturday) <-Pushed ahead by 2 dates to Monday
Tuesday (previously Sunday) <-Pushed ahead by 2 dates to Tuesday
Wednesday (previously Monday) <-Pushed ahead 2 dates to Wednesday due to weekends incrementing the dayCount by 2
Thursday <--- etc. etc.
Thanks a lot for the help folks, can move on now finally :>
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");
}
}
Friends,
I am looking to calculate the difference in days.
Hey suppose if I enter 31st Aug 23:59:00 and next date 1 Sept 00:02:00 , I need to show the record as 1 day.
Please help me for this one.
Right now I am calculating the same using .getTimeInMillis() but it is not giving me expected results for the date condition mentioned above.
I you look for day and time difference then, use my code
public class AndroidWebImage extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Date sdate=Calendar.getInstance().getTime();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
String setDate = "13/09/12 10:20:43";
Date AlarmDate=new Date(setDate);
String currentDate = format.format(sdate);
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(setDate);
d2 = format.parse(currentDate);
} catch (ParseException e) {
e.printStackTrace();
}
//Comparison
long diff = d1.getTime() - d2.getTime();
long diffSeconds = diff / 1000 % 60;
long days = (int) (diff / (1000 * 60 * 60 * 24));
long diffHours = (int) ((diff- (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
long diffMinutes = (int) (diff- (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * diffHours))/ (1000 * 60);
int curhour=sdate.getHours();
int curmin=sdate.getMinutes();
int alarmhour=AlarmDate.getHours();
int alarmmin=AlarmDate.getMinutes();
if(curhour==alarmhour && curmin==alarmmin)
{
Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
}
else if(curhour>=alarmhour && curmin>=alarmmin || curhour<=alarmhour && curmin<=alarmmin)
{
Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
}
}
}
You can't do this with millis, because you need to know where the day boundary falls (i.e. midnight). A millisecond either side of midnight means two different days.
You need to use a Calendar to determine how many days lie within the interval between your two dates. The JodaTime library has a lot of additional support for this kind of calculation.
See also Calculating the difference between two Java date instances
Your're just trying to find the number of days, right?
Try looking at this, it might have what you are looking for.
i made this code before, its may helps you
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* #author MErsan
*/
public class DateFormatter {
public static String formatDate(long time) {
StringBuilder result = new StringBuilder();
// 1- Check the year
// 2- Check the Month
// 3- Check the Day
// 4- Check the Hours
Date myDate = new Date(time);
Date todayDate = new Date(System.currentTimeMillis());
if (todayDate.getYear() - myDate.getYear() != 0) {
// Not same year, and should append the whole time
return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
}
// Same Year
// now Check the month
if (todayDate.getMonth() - myDate.getMonth() != 0) {
return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
// 16,
// 11:55
// PM
}
// Now Same Month
// Check the day
int daysDiff = todayDate.getDate() - myDate.getDate();
if (daysDiff == 1) {// Yesterday
result.append("Yesterday").append(' ');
result.append(new SimpleDateFormat("hh:mm a").format(myDate));
return result.toString();
} else if (daysDiff != 0) {
return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
// 16,
// 11:55
// PM
}
// Same Day :')
// Check the hour
int hoursDiff = todayDate.getHours() - myDate.getHours();
if (hoursDiff < 0) {// Invalid Time
// :#
result.append("Today").append(' ');
result.append(new SimpleDateFormat("hh:mm a").format(myDate));
return result.toString();
} else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
result.append("Today").append(' ');
result.append(new SimpleDateFormat("hh:mm a").format(myDate));
return result.toString();
} else if (hoursDiff != 0) {// Hours Diff less than 3 hours, but not
// current hour
int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
result.append("Before").append(' ');
result.append(hoursDiff).append(' ');
result.append("Hours").append(' ');
result.append("and").append(' ');
result.append(Math.abs(mintuesDiff)).append(' ');
result.append("Minutes");
System.err.println("Case 6");
return result.toString();
} else if (hoursDiff == 0) {// Same Hours
int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
if (mintuesDiff < 1) {// Seconds Only {Same Minute}
int secondsDiff = todayDate.getSeconds() - myDate.getSeconds();
result.append("Before").append(' ');
result.append(Math.abs(secondsDiff)).append(' ');
result.append("Seconds");
return result.toString();
} else {
result.append("Before").append(' ');
result.append(Math.abs(mintuesDiff)).append(' ');
result.append("Minutes");
return result.toString();
}
}
// Default
return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
}
}
import java.util.Calendar;
public class DateDifference
{
public static void main(String[] args)
{
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(2012, 01, 10);
calendar2.set(2012, 07, 01);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Time in days: " + diffDays + " days.");
}
}
You need to get rid of the timestamps and then subtract dates to get the difference in dates or you can use Joda-time as below:
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;
Date past = new Date(112, 8, 1);
Date today = new Date(112, 7, 30);
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays();
Re-post:
There's a simple solution, that at least for me, is the only feasible solution.
The problem is that all the answers I see being tossed around - using Joda, or Calendar, or Date, or whatever - only take the amount of milliseconds into consideration. They end up counting the number of 24-hour cycles between two dates, rather than the actual number of days. So something from Jan 1st 11pm to Jan 2nd 1am will return 0 days.
To count the actual number of days between startDate and endDate, simply do:
// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;
// Find the difference, duh
long daysBetween = endDay - startDay;
This will return "1" between Jan 2nd and Jan 1st. If you need to count the end day, just add 1 to daysBetween (I needed to do that in my code since I wanted to count the total number of days in the range).
I have the following two methods:
private long getTimeInMilliseconds()
{
Calendar c = Calendar.getInstance();
if(c.get(Calendar.DAY_OF_MONTH) == 21)
{
c.set(Calendar.MONTH, Calendar.MONTH + 1 );
c.set(Calendar.DAY_OF_MONTH, 1);
}
else
c.set(Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH + 10);
if(c.get(Calendar.MONTH) > 11)
c.set(Calendar.MONTH, 0);
return c.getTimeInMillis();
}
public static void remainingTime(L2PcInstance player)
{
long now = System.currentTimeMillis();
long then = player.getExpBoostTime();
long time = then - now;
int hours = (int) (time / 3600000);
player.sendMessage(hours+ " hours remaining until your EXP BOOST PERIOD ends");
}
I want getTimeInMillisSeconds() to return the time 10 days later. I want remainingTime() to show how many days (in hours) remain.
With the code above, it shows 4 days remaining and not 10.
Can anybody help?
You are making a mistake in the set() method.
It should be
c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 10);
However, your approach is far from being the best. The one suggested in another answer (adding 10 * 24 * 60 * 60 * 1000 milliseconds to the current time) is far better IMHO.
The best way to get "ten days from now" is to use timestamps/milliseconds.
You can get the current time in milliseconds from a calendar like this:
Calendar someCalendar = new Calendar();
long someTimestamp = someCalendar.getTimeInMillis();
Once you get that, you can add ten days to it (again in milliseconds):
long tenDays = 1000 * 60 * 60 * 24 * 10;
long tenDaysFromNow = someTimestamp + tenDays;