how to count the seconds in java? - java

I'm trying to understand how I could go about keeping track of the seconds that an object has been created for.
The program I'm working on with simulates a grocery store.
Some of the foods posses the trait to spoil after a set amount of time and this is all done in a subclass of an item class called groceryItem. The seconds do not need to be printed but are kept track of using a currentTime field and I don't quite understand how to count the seconds exactly.
I was looking at using the Java.util.Timer or the Java.util.Date library maybe but I don't fully understand how to use them for my issue.
I don't really have a very good understanding of java but any help would be appreciated.

You can use either long values with milliseconds since epoch, or java.util.Date objects (which internally uses long values with milliseconds since epoch, but are easier to display/debug).
// Using millis
class MyObj {
private final long createdMillis = System.currentTimeMillis();
public int getAgeInSeconds() {
long nowMillis = System.currentTimeMillis();
return (int)((nowMillis - this.createdMillis) / 1000);
}
}
// Using Date
class MyObj {
private final Date createdDate = new java.util.Date();
public int getAgeInSeconds() {
java.util.Date now = new java.util.Date();
return (int)((now.getTime() - this.createdDate.getTime()) / 1000);
}
}

When you create your object call.
Date startDate = new Date();
After you are done call;
Date endDate = new Date();
The number of seconds elapsed is:
int numSeconds = (int)((endDate.getTime() - startDate.getTime()) / 1000);

Related

Volatile String Java

I need to have a volatile string, that displays time.
I declared it like this:
public static volatile String timeTaken;
Later I assign current time to it like this:
DateFormat time = new SimpleDateFormat("HH:mm:ss");
long start = System.currentTimeMillis();
timeTaken = "Picture taken at " + time.format(start);
It is never changed and I want to use it in other threads just to display it as info.
Is it enough for it to be thread-safe? Thanks!

Java getting current date without creating a new Date object

I have a game that loops. I need to check the current number of milliseconds. I don't want to create a new Date object just to get the number of milliseconds that has passed. Is there a way to get the current time without creating a new Date object every iteration of my game loop?
Example:
Date d = new Date();
while(true)
{
long currentTime = d.getCurrentTime();
}
In the above code, the value of the currentTime variable would continuously change.
Rather than using Date, you can access the static method
long currentTime = System.currentTimeMillis()
This returns the current time of the given system in milliseconds.

Timestamping Using Date Class Java

I am trying to use the Date class to get the current time each time my loop executes. So far I have:
Date timeNow = new Date();
while(true){
System.out.println(timeNow.getTime()); //prints current time
Thread.sleep(10000);//sleep 10 secounds
}
When the time is reprinted it just shows the same time every print instead of being 10 seconds later. What am I doing wrong? Thanks for the help.
You created timeNow outside of the while loop. The time for this object is captured at construction time. When you move it within the scope of the while loop, you'll get a new object every time which represents the time it was created.
while(true) {
Date timeNow = new Date();
System.out.println(timeNow.getTime()); //prints current time
Thread.sleep(10000);//sleep 10 secounds
}
Note that the default constructor of Date is equivalent to..
Date timeNow = new Date(System.currentTimeMillis());
When you execute Date myDate = new Date() you create a Date object with the current system time.
Anytime you call myDate.getTime() you will get the same output, the time as at whenever you created the object.
To see a different time, you would need to create a new Date object after each Thread.sleep(10000), like this:
while(true) {
Date myDate = new Date()
System.out.println(myDate.getTime()); //prints current time
Thread.sleep(10000);//sleep 10 seconds
}

Time difference calculation issues

I have a table called by name Symbols in my Application which will be updated continously for every 8 minutes
Each record inside the Symbol table has got a attribute by name updated-at and whose value is in timestamp as shown
"updated_at" : NumberLong("1375715967249")
I have a task to show the updated data to the users from the symbols table
In case the symbol is not updated for 9 minutes , i need to executed a particular task and if updated a different task
I was following this logic , please let me know if this has got any loop holes ?? ( I mean like day like settings --- or any such )
package com;
public class UnixTimeConversion {
public static void main(String args[]) {
long timeStamp = 1375715967249l;
java.util.Date date = new java.util.Date();
long currtime = date.getTime();
if ((currtime - timeStamp) > 600000) {
System.out.println("Greater than 10 minutes since executed");
} else {
System.out.println("Lesser than 10 minutes since executed");
}
}
}
Better to try in this way
long timeStamp = 1375715967249l;
long currTime = System.currentTimeMillis();
if ((currTime - timeStamp) > 10*60*1000) {
System.out.println("Greater than 10 minutes since executed");
} else {
System.out.println("Lesser than 10 minutes since executed");
}
10min = 10*60*1000 ms
UNIX timestamps don't care about Timezones, UTC leap seconds or anything. It's just a number linearly measuring the passing of time. If you don't care about wallclock time either, there's no problem. You just have to take care that you convert your source material to UNIX timestamps in the right manner.

How to determine if the specific time is between given range?

Problem: I have a list containg hours, for example:
08:15:00
08:45:00
09:00:00
12:00:00
...
application is allowing user to make an appointment for a specific hour let'say: 8:15:00, each meeting takes half an hour.
Question: How to determine if there is a slot needed for appointment like this? I know that Calendar class have methods before() nad after(), but it doesn'solve my problem. I mean if there is appointment at 12:00 and another one at 12:00, how to prevent before making another one at 12:15?
edit:
I've tried using methods I mentioned before, like:
Calendar cal1 = Calendar.getInstance(); // for example 12:00:00
Calendar cal2 = Calendar.getInstance(); // for exmaple 12:30:00
Calendar userTime = Calendar.getInstance(); // time to test: 12:15:00
if(user.after(cal1)&& user.before(cal2)){
... // do sth
}
Check if the date to check is between the two provided:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
boolean isAvailable = (before.getTime() < toCheck.getTime()) && after.getTime() > toCheck.getTime();
To book for a determinate hour, I would do a class with two dates and a method to check this:
public class Appointment{
private Date start;
private Date end;
public boolean isBetween(Date toCheck){....}
}
Then you can simply do an Schedule class extending ArrayList, adding a method isDateAvailable(Date toCheck), iterating the list of Appointments and checking that there is no one conflicting.
I'd have some kind of appointment class with either a start timestamp and a duration or a start time and an end time. Then when adding new appointments to the schedule, check that the appointment with the start time before the new appointment doesn't run over the start time of the proposed new appointment.
Well how you would do it specifically depends on how you are storing your data, format, etc., but generally what you would do is simply check if there is an appointment for any time between the requested time to the requested time + requested length.
// Example (using int time(1 = 1 minute), assuming that appointments can only be at 15min intervals)
boolean isHalfHourTimeSlotAvaliable(int time) {
for (int i = 0; i < appointments.size(); i++) {
if (appointments.get(i).time == time || appointments.get(i).time == time + 15) {
return false;
}
}
return true;
}

Categories

Resources