I want to represent time with my time class. I can't use get and set methods.Only I can use listed methods on the code.But it doesn't work.
It returns 0:0:0.
public int addHours(int hours)
{
if(hours>=0&&hours<=23)
{
return hours;
}
return 0;
}
public int addMinutes(int minutes)
{
if(minutes>=0&&minutes<=59)
{
return minutes;
}
return 0;
}
public int addSeconds(int seconds)
{
if(seconds>=0&&seconds<=59)
{
return seconds;
}
return 0;
}
public String showTime()
{
return hours+":"+minutes+":"+seconds;
}
}
your code does nothing.
you need to do something like this:
public void addHours( int hours ){
this.hours += hours; // add hours
this.hours %= 24; // roll over at 24 hours
}
public void addMinutes( int minutes ){
this.minutes += minutes; // add minutes
addHours(this.minutes/60); // carry over to hours
this.minutes %= 60; // roll over at 60 minutes
}
public void addSeconds( int seconds ){
this.seconds += seconds; // add seconds
addMinutes(seconds/60); // carry over to minutes
this.seconds %= 60; // roll over at 60 seconds
}
(it probably won't matter, but this is not thread safe at all)
but this is generally a bad idea. Java 8 has a beautiful time api, pre Java-8 there is the JodaTime library (which is actually the basis of the Java 8 time api). It seems what you want to do could benefit from LocalTime:
LocalTime t = LocalTime.of(13,50,27).addHours(1).addMinutes(1).addSeconds(1);
System.out.println(t.toString());
// prints 14:51:28
Use java.util.Calendar and java.text.SimpleDateFormat:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.add(Calendar.HOUR, 5);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(cal.getTime()));
Related
I want to test current time.
Is it the same between the two times?
-With the note, I've already done a job
function to enter the start time
and the time to end.
Now i want to complete the special function.
i'm testing this entry value between the two times.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int hourStart = 5;
int minuteStart = 30;
String PMAMStart="AM";
int hourEnd = 6;
int minuteEnd = 30;
String PMAMEnd="AM";
boolean checkTime= checkCurrentTimeBetweenTowVlue(hourStart,minuteStart,PMAMStart,hourEnd,minuteEnd,PMAMEnd);
}
private boolean checkCurrentTimeBetweenTowVlue(int hStart,int mStart,String ampmStart,int hEnd,int mEnd,String ampmEnd){
Calendar cal = Calendar.getInstance();
return false;
}
}
In your case, you can set the individual calendar fields such as AM_PM, Hour, and Minute for both start and end dates, convert the time to minutes, and then find the difference between the times. Here is the solution:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int hourStart = 5;
int minuteStart = 30;
String PMAMStart="AM";
int hourEnd = 6;
int minuteEnd = 30;
String PMAMEnd="AM";
boolean checkTime= checkCurrentTimeBetweenTwoValues(hourStart,minuteStart,PMAMStart,hourEnd,minuteEnd,PMAMEnd);
if (checkTime) {
System.out.println("Time is Same");
} else {
System.out.println("Time is not Same");
}
}
private boolean checkCurrentTimeBetweenTwoValues(int hStart,int mStart,String ampmStart,int hEnd,int mEnd,String ampmEnd){
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
if (ampmStart.equalsIgnoreCase("AM")) {
startCalendar.set(Calendar.AM_PM, 0);
} else {
startCalendar.set(Calendar.AM_PM, 1);
}
startCalendar.setTimeZone(TimeZone.getDefault());
startCalendar.set(Calendar.HOUR, hStart);
startCalendar.set(Calendar.MINUTE, mStart);
if (ampmEnd.equalsIgnoreCase("AM")) {
endCalendar.set(Calendar.AM_PM, 0);
} else {
endCalendar.set(Calendar.AM_PM, 1);
}
endCalendar.setTimeZone(TimeZone.getDefault());
endCalendar.set(Calendar.HOUR, hEnd);
endCalendar.set(Calendar.MINUTE, mEnd);
long timeDifference = TimeUnit.MILLISECONDS.toMinutes(
Math.abs(endCalendar.getTimeInMillis() - startCalendar.getTimeInMillis()));
System.out.println(("Time Difference: " + timeDifference));
return (timeDifference == 0);
}
}
You can also use TimeUnit.MILLISECONDS.toSeconds to check for Seconds but for that, you need to set the Seconds component of the Calendar instance.
Regards,
AJ
If you can use Java 8 (beginning with API level 26 in Android) or if you are willing / able / allowed to import a very useful library that enables java.time support to lower API levels, then the following might be a neat solution:
public static boolean isNowBetween(int startHour, int startMinute, int endHour, int endMinute) {
LocalTime start = LocalTime.of(startHour, startMinute);
LocalTime end = LocalTime.of(endHour, endMinute);
LocalTime now = LocalTime.now();
return now.isAfter(start) && now.isBefore(end);
}
Get current minutes and hours from cal object. Convert start, end, current time into minutes, then it will be easy to compare.
private boolean checkCurrentTimeBetweenTowVlue(int hStart,int mStart,String ampmStart,int hEnd,int mEnd,String ampmEnd){
Calendar cal = Calendar.getInstance();
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
if(ampmStart.equals("PM")){
hStart += 12;
}
int minutes_start = hStart*60 + mStart;
if(ampmEnd.equals("PM")){
hEnd += 12;
}
int minutes_end = hEnd*60 + mEnd;
int minutes_curr = hours*60 + minutes;
if(minutes_curr>minutes_start && minutes_curr<minutes_end){
return true;
}
return false;
}
import java.text.SimpleDateFormat;
import java.util.Date;
public class Rate_Per_Hour {
public static void main(String[] args) {
String TimeStart = "09.30.00 am";
String TimeEnd= "10.10.00 am";
SimpleDateFormat format = new SimpleDateFormat("hh.mm.ss a");
int total=0;
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(TimeStart);
d2 = format.parse(TimeEnd);
long diff = d2.getTime() - d1.getTime();
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffMinutes = diff / (60 * 1000) % 60;
if (diffMinutes <= 30) {
total = 20;
}
else if (diffHours <=1){
total = 35;
}
System.out.println("Rs." +total);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want output like this:
(Fixed rate per hour for this is Rs.35 )
For 30 min = Rs.20
For 40 min = Rs.25 and so on......
For 1 hour = Rs.35
For 1 hour 10 min = Rs.40
Please help me, figure out how I can do this.
Since the rate increases by 5 every 10 minutes, so just use a simple function to return the rate:
public double rate(int minutes)
{
return 20 + 5*((minutes - 30)/10);
}
Calculate the number of minutes and then pass it as an argument in that function to get the rate. Also, try to keep your code as short as possible but at the same time, simple.
if you need something more flexible rather than fixed rate you could implement an enum with predefined stops
you could define any rate you want for a given time.
for example if long running tasks shall gain higher rates (from your question it was not obvious to me if this rate shall be just the calculated value as in Manish Kundu's answer or if other values might get assigned.)
with this code you could assign higher rates for long running jobs (for example in computer games, jobs that are harder to achieve you return a higher rate or you lower the rate because the player took too much time...)
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class TimeMain {
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh.mm.ss[ ]a");
public enum Rate {
STOP0(0, 0, 0), // default
STOP1(0, 30, 20), // 30 mins -> Rs.20
STOP2(0, 40, 25), // 40 mins -> Rs.25
STOP3(1, 0, 35), // 1 hour -> Rs.35
STOP4(1, 10, 40); // 1 hour 10 minutes -> Rs.40
int minutes = 0;
int rate = 0;
/*
* hours is actually not needed as 1h10 = 70mins...
*/
private Rate(int hours, int minutes, int rate) {
this.minutes = minutes + hours * 60;
this.rate = rate;
}
public static Rate from(String timeStart, String timeEnd) {
LocalTime time1 = LocalTime.parse(timeStart.toUpperCase(), dateTimeFormatter);
LocalTime time2 = LocalTime.parse(timeEnd.toUpperCase(), dateTimeFormatter);
long minutesBetween = ChronoUnit.MINUTES.between(time1, time2);
for (int i = 0; i < Rate.values().length; i++) {
Rate r = Rate.values()[i];
if (r.minutes > minutesBetween) {
return Rate.values()[i-1];
}
}
return STOP0;
}
public String toString() {
return String.format("Rs.%s", rate);
}
}
public static void main(String... args) {
String timeStart = "09.30.00 am";
String timeEnd = "10.10.00 am";
System.out.println(Rate.from(timeStart, timeEnd));
}
}
What I want to do?
I want to return time and display based on user's input. Say, user enters in console starthour: 23 startminute: 45 duration (in min): 30 then the period for start time will be PM offcourse and you can see below I calculated the start time based on the above things, but issue is calculating the endtime. For example, in the above start times, the end time should become 00:15 with the period AM and not PM like start hour.
What I did?
public String toString(){
int h = (getHour()==0 || getHour()==12) ? getHour() : getHour()%12;
String period = (getHour()<12)? "AM" : "PM";
return String.format("%02d:%02d %s", h, getMinute(), period);
}
What to do?
The above formula calculates the start time and its period, correctly, but I need a similar formula that can calculate the endhour correctly based on start hour, start minutes and duration entered by the user.
Basically, above mentioned code needs to be manipulated to figure out the endhour, endminute and its period.
Note: Please don't tell about local time use for getting end time and period. Thankyou
EDIT: Here is what I did now:
public String toString(){
int endh = (getEndHour()==0 || getEndHour()==12) ? getEndHour() : getEndHour()%12;
String period = ((getEndHour() + duration) <12)? "AM" : "PM";
return String.format("%02d:%02d %s", endh, getEndHour(), period);
}
you should use 60 modulo for simplicity. here it is
public class Timer {
int hour;
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public void addDuration(int duration) {
hour = hour + (minutes + duration)/ 60;
minutes = (minutes + duration) % 60;
}
int minutes;
#Override
public String toString() {
int h = (getHour() == 0 || getHour() == 12) ? getHour()
: getHour() % 24;
String period = (getHour() < 12) ? "AM" : "PM";
return String.format("%02d:%02d %s", h, getMinutes(), period);
}
public static void main(String args[]) {
Timer time = new Timer();
time.setHour(23);
time.setMinutes(45);
System.out.println(time.getHour());
time.addDuration(30);
System.out.println(time.getHour());
System.out.println(time);
}
}
I am really new to programming. I am doing an assignment for my intro to Java. In my assignment, we need to find the total number of seconds since midnight and changed this number to hours, minutes and seconds to show the current time. I have small problem. when I test my code, the totalseconds show 0! any help would be appreciated. Sorry the code is a chaos
package clock;
import java.text.DecimalFormat;
import java.util.Calendar; // to get current time
public class Clock {
public static int totalseconds;
public static int seconds;
public static int minutes;
public static int hours;
public static int test;
public Clock(int hours, int minutes, int seconds ) {
setHours(hours);
setMinutes(minutes);
setSeconds(seconds);
}
// use current time
public Clock() {
Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
long secondsPassed = passed / 1000;
totalseconds = (int) secondsPassed;
}
public void tick() {
addSecond();
}
private void addSecond() {
seconds = totalseconds%60;
}
private void addMinute() {
minutes = totalseconds/60 % 60;
}
private void addHour() {
hours = totalseconds / 3600;
}
public String toString() {
DecimalFormat f = new DecimalFormat("00");
return f.format(hours) + ":" + f.format(minutes) + ":" + f.format(seconds);
}
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
// the total number of minutes sinces midnight
public int getTotalMinutes() {
return totalseconds / 60 % 60;
}
// the total number of seconds since midnight
public int getTotalSeconds() {
return totalseconds;
}
public void setHours(int hours) {
if (hours > 23 || hours < 0) {
this.hours = 0;
}
else
this.hours = hours;
}
public void setMinutes(int minutes) {
if (minutes > 59 || minutes < 0)
this.minutes = 0;
else
this.minutes = minutes;
}
public void setSeconds(int seconds) {
if (seconds > 59 || seconds < 0)
this.seconds = 0;
else
this.seconds = seconds;
}
// reset hours, minutes and seconds to zero
public void reset() {
hours = minutes = seconds = 0;
}
public static void main(String [] args){
System.out.println("this is total seconds " + test + totalseconds );
}
}
Change main to this.
public static void main(String [] args){
Clock clock = new Clock();
System.out.println("this is total seconds " + test + totalseconds );
}
New you make an instance of Clock and the constructor is called, where all your magic happens.
I agree with what #shmosel suggested. There seems to be confusion in how to use instance variable. Further, I think you should take advantages of Java 8 methods for your time part.
class Clock {
private int totalseconds;
private int seconds;
private int minutes;
private int hours;
int test;
public Clock(int hours, int minutes, int seconds) {
setHours(hours);
setMinutes(minutes);
setSeconds(seconds);
}
// use current time
public Clock() {
LocalTime now = LocalTime.now(ZoneId.systemDefault());
totalseconds = now.toSecondOfDay();
}
public void tick() {
addSecond();
}
private void addSecond() {
seconds = totalseconds % 60;
}
private void addMinute() {
minutes = totalseconds / 60 % 60;
}
private void addHour() {
hours = totalseconds / 3600;
}
public String toString() {
DecimalFormat f = new DecimalFormat("00");
return f.format(hours) + ":" + f.format(minutes) + ":" + f.format(seconds);
}
public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}
// the total number of minutes since midnight
public int getTotalMinutes() {
return totalseconds / 60 % 60;
}
// the total number of seconds since midnight
public int getTotalSeconds() {
return totalseconds;
}
public void setHours(int hours) {
if (hours > 23 || hours < 0) {
this.hours = 0;
} else
this.hours = hours;
}
public void setMinutes(int minutes) {
if (minutes > 59 || minutes < 0)
this.minutes = 0;
else
this.minutes = minutes;
}
public void setSeconds(int seconds) {
if (seconds > 59 || seconds < 0)
this.seconds = 0;
else
this.seconds = seconds;
}
// reset hours, minutes and seconds to zero
public void reset() {
hours = minutes = seconds = 0;
}
}
public class SecondsSinceMidnight {
public static void main(String[] args) {
Clock myClock = new Clock();
System.out.println("Total seconds that elapsed since midnight:" + myClock.getTotalSeconds());
System.out.println("Converted to Minutes: " + myClock.getTotalMinutes());
}
}
I have some documents and its created time is in milliseconds.
I need to separate them as Today, Yesterday, Last 7 Days, Last 30 Days, More than 30 Days.
I used the following code:convertSimpleDayFormat(1347022979786);
public static String convertSimpleDayFormat(Long val) {
long displayTime = System.currentTimeMillis() - val;
displayTime = displayTime/86400000;
String displayTimeVal = "";
if(displayTime <1)
{
displayTimeVal = "today";
}
else if(displayTime<2)
{
displayTimeVal = "yesterday";
}
else if(displayTime<7)
{
displayTimeVal = "last7days";
}
else if(displayTime<30)
{
displayTimeVal = "last30days";
}
else
{
displayTimeVal = "morethan30days";
}
return displayTimeVal;
}
I am subtracting the current time and passing the milliseconds and converting to one day.
But the issue I'm facing is, I couldn't calculate the exact time for the date in milliseconds.
I want to calculate for Today as: From Midnight 00:00 to Midnight 24:00. (Exactly for 24 hours.)
Similarly I want to exactly convert the Milliseconds into Today, Yesterday, Last 7 days, Last 30 Days and More than 30 Days.
private static Calendar clearTimes(Calendar c) {
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
return c;
}
public static String convertSimpleDayFormat(long val) {
Calendar today=Calendar.getInstance();
today=clearTimes(today);
Calendar yesterday=Calendar.getInstance();
yesterday.add(Calendar.DAY_OF_YEAR,-1);
yesterday=clearTimes(yesterday);
Calendar last7days=Calendar.getInstance();
last7days.add(Calendar.DAY_OF_YEAR,-7);
last7days=clearTimes(last7days);
Calendar last30days=Calendar.getInstance();
last30days.add(Calendar.DAY_OF_YEAR,-30);
last30days=clearTimes(last30days);
if(val >today.getTimeInMillis())
{
return "today";
}
else if(val>yesterday.getTimeInMillis())
{
return "yesterday";
}
else if(val>last7days.getTimeInMillis())
{
return "last7days";
}
else if(val>last30days.getTimeInMillis())
{
return "last30days";
}
else
{
return "morethan30days";
}
}
It's a small hack, not severely tested. Use at own risk. I've made it extensible so you can add new durations.
public static String prettyTimeStamp(long timeStamp) {
Calendar c = Calendar.getInstance();
c.clear(Calendar.HOUR_OF_DAY);
c.clear(Calendar.MINUTE);
c.clear(Calendar.SECOND);
c.clear(Calendar.MILLISECOND);
long today = c.getTimeInMillis();
final long oneDay = 24 * 60 * 60 * 1000L;
final long[] durations = new long[] { today - oneDay, today,
today + 7 * oneDay, today + 30 * oneDay };
final String[] labels = "Yesterday,Today,Last 7 days,Last 30 Days,More than 30 Days"
.split(",");
int pos = Arrays.binarySearch(durations, timeStamp);
return labels[pos < 0 ? ~pos : pos];
}
By the way, you should really just use a Library like PrettyTime