Check if current time is between 2 times. JAVA - java

I'm new at coding and I want my program to do something if the current time is between 2 times.
Example:
Current time = 8:25AM
If current time is between 8:00AM and 8:50AM, print 'something' into console.
Is there a way for my program to get the current time automatically? Calendar Class?
Please Help!
Matthew

You can get current time instantiating a new java.util.Object
Date current = new Date();
Then you can play with after() and before() methods
Hope this helps,
Alberto

String starttime = "08:00:00";
String endtime = "08:50:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(starttime);
Date date2 = format.parse(endtime);
Calendar cal = Calendar.getInstance();
String currenttime = format.format(cal.getTime());
Date datenow = format.parse(currenttime)
if (date1.getTime() < datnow.getTime() && date2.getTIme() > datenow.getTime())
System.out.println("Time is within defined borders.");
I dont have a compiler now . This should work fine .

Related

Set new time after the actual one

I'm trying to create a method that prints e.g. actual time of arrival (now) and then it prints the time of departure which I want to set plus 3 minutes compared to the first one.
public void updateTimes(){
SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
this.arrivalTime = new Date();
this.departureTime = this.arrivalTime.plusMinutes(3);
}
Departure time doesn't work as intended.
Any help is welcome.
java.util.Date not have plusMinutes.
It can be better if you use Java 8, with java.time library :
LocalTime arrivalTime = LocalTime.now();//Current time
LocalTime departureTime = arrivalTime.plusMinutes(3);//plus 3 minutes to the time
//Then you can format the time
String result = departureTime.format(DateTimeFormatter.ofPattern("H:mm"));
Another solution using Calendar looks like:
Calendar cal = Calendar.getInstance();
cal.setTime(arrivalTime); // only if different from "now"
cal.add(Calendar.MINUTE, 3);
departureTime = cal.getTime();
I think you can do something like below:
SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
Date date = new Date();
System.out.println("arrival time = " + sdf.format(date));
int min = date.getMinutes();
date.setMinutes(min+3);
System.out.println("departure time = " + sdf.format(date));

How to add current time to a previous date in java?

I was trying to add current time into previous date. But it was adding in current date with time not with previous date.
see my bellow code:
Date startUserDate = ;//this is my previous date object;
startUserDate.setTime(new Date().getTime());// here i'm trying to add current time in previous date.
System.out.println("current time with previous Date :"+startUserDate);
In previous date there is no time and i want to add current time in previous date.I can do this, please help me out.
Use calendar object
Get instance of calendar object and set your past time to it
Date startUserDate = ;
Calendar calendar = Calendar.getInstance();
calendar.settime(startUserDate);
Create new calendar instance
Calendar cal = Calendar.getInstance();
cal.settime(new Date());
format the date to get string representation of time of current date
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentdate = sdf.format(cal.getTime());
split that string to get hour minute and second object
String hh = expiry.split(":")[0];
String mm = expiry.split(":")[1];
String ss = expiry.split(":")[2];
add it to the previous calendar object
calendar .add(Calendar.HOUR_OF_DAY, hh);
calendar .add(Calendar.MINUTE, mm);
calendar .add(Calendar.SECOND, ss);
this date will have current time added to your date
Date newDate = calendar.getTime;
Use Calendar:
first set the date/time of the first calendar object to the old date
object use as second Calendar object to set the current time on the
first calendar object then convert it back to date
as follow:
//E.g. for startUserDate
Date startUserDate = new Date(System.currentTimeMillis() - (24L * 60L * 60L * 1000L) - (60L * 60L * 1000L));//minus 1 day and 1 hour
Calendar calDateThen = Calendar.getInstance();
Calendar calTimeNow = Calendar.getInstance();
calDateThen.setTime(startUserDate);
calDateThen.set(Calendar.HOUR_OF_DAY, calTimeNow.get(Calendar.HOUR_OF_DAY));
calDateThen.set(Calendar.MINUTE, calTimeNow.get(Calendar.MINUTE));
calDateThen.set(Calendar.SECOND, calTimeNow.get(Calendar.SECOND));
startUserDate = calDateThen.getTime();
System.out.println(startUserDate);
The second Calendar object calTimeNow can be replaced with Calendar.getInstance() where it is used.
You can do it using DateFormat and String, here's the solution that you need:
Code:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String timeString = df.format(new Date()).substring(10); // 10 is the beginIndex of time here
DateFormat df2 = new SimpleDateFormat("MM/dd/yyyy");
String startUserDateString = df2.format(startUserDate);
startUserDateString = startUserDateString+" "+timeString;
// you will get this format "MM/dd/yyyy HH:mm:ss"
//then parse the new date here
startUserDate = df.parse(startUserDateString);
Explanation:
Just convert the current date to a string and then extract the time from it using .substring() method, then convert your userDate to a string concatenate the taken time String to it and finally parse this date to get what you need.
Example:
You can see it working in this ideone DEMO.
Which takes 02/20/2002 in input and returns 02/20/2002 04:36:14 as result.
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
ZoneId zone = ZoneId.systemDefault();
LocalDate somePreviousDate = LocalDate.of(2018, Month.NOVEMBER, 22);
LocalTime timeOfDayNow = LocalTime.now(zone);
LocalDateTime dateTime = somePreviousDate.atTime(timeOfDayNow);
System.out.println(dateTime);
When I ran the code just now — 16:25 in my time zone — I got this output:
2018-11-22T16:25:53.253892
If you’ve got an old-fashioned Date object, start by converting to a modern Instant and perform further conversion from there:
Date somePreviousDate = new Date(1_555_555_555_555L);
LocalDate date = somePreviousDate.toInstant().atZone(zone).toLocalDate();
LocalTime timeOfDayNow = LocalTime.now(zone);
LocalDateTime dateTime = date.atTime(timeOfDayNow);
2019-04-18T16:25:53.277947
If conversely you need the result as an old-fashioned Date, also convert over Instant:
Instant i = dateTime.atZone(zone).toInstant();
Date oldfasionedDate = Date.from(i);
System.out.println(oldfasionedDate);
Thu Nov 22 16:25:53 CET 2018
Link
Oracle tutorial: Date Time explaining how to use java.time.
The getTime method returns the number of milliseconds since 1970/01/01 so to get the time portion of the date you can either use a Calendar object or simply use modula arithmetic (using the above milliseconds value and the MAX millseconds in a day) to extract the time portion of the Date.
Then when you have the time you need to add it to the second date,
but seriously, use http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
and use things like get (HOUR) and get (MINUTE) etc. which then you can use with set (HOUR, val)
You need to use Calendar class to perform addition to Dateobject. Date's setTime() will set that time in Date object but not add i.e it will overwrite previous date. new Date().getTime() will not return only time portion but time since Epoch. Also, how did you manipulated , startUserDate to not have any time (I mean , was it via Calendar or Formatter) ?
See Answer , Time Portion of Date to calculate only time portion,
long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
Date now = Calendar.getInstance().getTime();
long timePortion = now.getTime() % MILLIS_PER_DAY;
then you can use something like, cal.add(Calendar.MILLISECOND, (int)timePortion); where cal is Calendar object corresponding to your startUserDate in your code.
Calendar calendar = Calendar.getInstance();
calendar.setTime(startUserDate );
//new date for current time
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentdate = sdf.format(new Date());
String hhStr = currentdate.split(":")[0];
String mmStr = currentdate.split(":")[1];
String ssStr = currentdate.split(":")[2];
Integer hh = 0;
Integer mm = 0;
Integer ss = 0;
try {
hh = Integer.parseInt(hhStr);
mm = Integer.parseInt(mmStr);
ss = Integer.parseInt(ssStr);
}catch(Exception e) {e.printStackTrace();}
calendar.set(Calendar.HOUR_OF_DAY, hh);
calendar.set(Calendar.MINUTE, mm);
calendar.set(Calendar.SECOND, ss);
startUserDate = calendar.getTime();

Compare current date with date from property file

I am getting a hard coded date from the property file , which is of the format dd-MMM-yyyy.
Now i need to compare it with current date of same format. For that purpose , i cooked up this piece of code :
Date convDate = new Date();
Date currentFormattedDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
convDate = new SimpleDateFormat("dd-MMM-yyyy").parse("20-Aug-2013");
currentFormattedDate = new Date(dateFormat.format(currentFormattedDate));
if(currentFormattedDate.after(convDate) || currentFormattedDate.equals(convDate)){
System.out.println("Correct");
}else{
System.out.println("In correct");
}
But eclipse tells me that new Date has been depreciated. Does any one know of any alternative way of doing this ? I am going crazy over this. Thanks !
One of the way is to use the Calendar class and its after() , equals() and before() methods.
Calendar currentDate = Calendar.getInstance();
Calendar anotherDate = Calendar.getInstance();
Date convDate = new SimpleDateFormat("dd-MMM-yyyy").parse("20-Aug-2013");
anotherDate.setTime(convDate);
if(currentDate .after(anotherDate) ||
currentDate .equals(anotherDate)){
System.out.println("Correct");
}else{
System.out.println("In correct");
}
You can also use Jodatime library , see this SO answer.
You should use the Date(long) constructor:
Date convDate = new Date(System.currentTimeMillis());
This way you'll avoid the deprecation warning and will get a Date instance with the system time.
Date represents number of milliseconds since the epoch. Why not just use the Date returned from
Date currentFormattedDate = new Date();
?

How to add some time in the system time?

I am trying to get the system date by using the following code . Now i want after adding 123 minutes it should automatically add 2 in hours and three in minutes how is it possible?
I am using the following code.
try{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
String s = sdf.format(date);
}
catch(Exception ex)
{
ex.printStackTrace();
}
Create a GregorianCalendar object: http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html add you hours/minutes/whatever you need to add and then get back a Date
This will work
DateFormat df = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
System.out.println(df.format(date));
long milSec=date.getTime();
long addMilSec=123*60*1000;
long sum=milSec+addMilSec;
Date d=new Date(sum);
System.out.println(df.format(d));
Create a Calendar object, instead of Date, and use add.
Example:
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, 123);
String s = sdf.format(c.getTime());
try like this
Calendar now = Calendar.getInstance();
now.setTime(YOUR_DATE_OBJECT);//pass your date here
now.add(Calendar.MINUTE, 50);//add 5o minutes
now.add(Calendar.SECOND, -50);// subtract 50 seconds

Date comparison in android

I'm facing some problems in comparing the current date and the date which is retrieved from Database.I just retrieved date from DataBase and Stored in a Date variable like this
String due_date_task = cursor.getString(cursor.getColumnIndex(dueDateOfTask));
SimpleDateFormat currentFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = currentFormater.parse(due_date_task);
Now,what i want is should check whether date which is retrieved from DataBase is Equivalent to CurrentDate or not.
Calendar currentDate = Calendar.getInstance();
Date date2 = currentDate.getTime();
if(date1.equals(date2))
System.out.println("Today Task");
i just want to check like this.Thanks in advance
For exact match including milliseconds, use getTime:
if(date.getTime() == date1.getTime()){
//do something
}
You can use this function:
private boolean compareDates(Calendar objCal1, Calendar objCal2) {
return ((objCal1.get(Calendar.YEAR) == objCal2.get(Calendar.YEAR))
&& (objCal1.get(Calendar.DAY_OF_YEAR) == objCal2.get(Calendar.DAY_OF_YEAR)));
}
creating the calendar objects:
Calendar objCal1 = new GregorianCalendar().setTime(date);
Calendar objCal2 = new GregorianCalendar().setTime(date1);
Try this way to get the current date,
Calendar calCurr = Calendar.getInstance();
Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis()); // see what it gives? dont know why?
Date date = new Date();
calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());// so added one month to it
Log.i("Time in mili of Current - after update", ""+calCurr.getTimeInMillis()); // now get correct
now create Calendar object for database value,
String due_date_task = cursor.getString(cursor.getColumnIndex(dueDateOfTask));
SimpleDateFormat currentFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date = currentFormater.parse(due_date_task);
Calendar start = Calendar.getInstance();
start.set(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
and now Compare both the Calendar objects
if(calCurr.equals(start))

Categories