Check current time against specific times in Java and Android Studio - java

I want to set a boolean value isBasePriceTime to false if the current time is equal to 6pm or after 6pm and is not between midnight and 6am the next day. However it keeps setting the isBasePriceTime to false if the current time of the day is for example 2pm.
private boolean checkCurrentTimePriceType()
{
/*Get the current price type depending on the time of the day the user wants to
get a cab */
Calendar today = Calendar.getInstance();
Date currentDate = today.getTime();
//creates a time for 6pm
String nightPriceFullTime = "18:00:00";
Date nightPriceTime = java.sql.Time.valueOf(nightPriceFullTime);
Calendar nightPriceDateCalendar = Calendar.getInstance();
nightPriceDateCalendar.setTime(nightPriceTime);
//creates a time for midnight
String nightPriceFullTimeMidnight = "00:00:00";
Date nightPriceTimeMidnight = java.sql.Time.valueOf(nightPriceFullTimeMidnight);
Calendar nightPriceMidnightDateCalendar = Calendar.getInstance();
nightPriceMidnightDateCalendar.setTime(nightPriceTimeMidnight);
//creates a time for 6am
String basePriceFullTime = "06:00:00";
Date basePriceTime = java.sql.Time.valueOf(basePriceFullTime);
Calendar basePriceDateCalendar = Calendar.getInstance();
basePriceDateCalendar.setTime(basePriceTime);
boolean isBasePriceTime;
//checks if the current time is or after 6pm, or if the the current time is between midnight and 6am
if(((today.getTime().after(nightPriceDateCalendar.getTime())) || (today.getTime().equals(nightPriceDateCalendar.getTime())))
|| ((today.getTime().before(basePriceDateCalendar.getTime())) && (today.getTime().after(nightPriceMidnightDateCalendar.getTime()))))
{
//user will pay a night time price
isBasePriceTime = false;
}
else
{
//user will pay a base time price
isBasePriceTime = true;
}
//return value of isNightPrice boolean variable
return isBasePriceTime;
}

Maybe this simplification will work for you:
int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); //Current hour
return currentHour < 18 //False if after 6pm

Using Jodatime:
LocalTime time = new LocalTime(/* Optional but recommended: specify timezone */);
return time.isAfter(LocalTime.of(18, 0))
|| time.isBefore(LocalTime.of(6, 0));
Using Java 8:
LocalTime time = LocalTime.now(/* Optional but recommended: specify timezone */);
return time.isAfter(LocalTime.of(18, 0))
|| time.isBefore(LocalTime.of(6, 0));
(Note that the class names are the same, but they are from different packages).

java.sql.Time.valueOf(nightPriceFullTime) will return January 1, 1970 18:00:00. You should use some other way to convert the Strings into dates. If you want to keep using this conversion method, you will have to change how you compare the time of the different calendars. For example:
if(nightPriceDateCalendar.get(Calendar.HOUR_OF_DAY) > today.get(Calendar.HOUR_OF_DAY) && ...){...}
Another approach will be this:
String time = "18:00:00";
SimpleDateFormat sdf = SimpleDateFormat("yyyy/MM/dd");
String onlyDate = sdf.format(new Date());
sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date dateAndTime = sdf.parse(onlyDate+" "+time);
Calendar nightPriceDateCalendar = Calendar.getInstance();
nightPriceDateCalendar.setTime(dateAndTime);

Related

Check my current time is exist between 7:00 PM -10.00 AM in java android

Example: my current time = 8:25 PM it means the current time is inside 7:00 PM to 10.00 AM. So how can I determined it & if inside show a message?
It's for a restaurant time restriction. from 7:00 PM to 10.00 AM time range user can't order anything.
try {
// Start Time
String string1 = "07:00 PM";
Date time1 = new SimpleDateFormat("hh:mm a").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
// End Time
String string2 = "10:00 AM";
Date time2 = new SimpleDateFormat("hh:mm a").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
// Get Current Time
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
String currenttime = sdf.format(date);
Date d = new SimpleDateFormat("hh:mm a").parse(currenttime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
System.out.println("Not possible to order now");
}
else
{
System.out.println("YES POSSIBLE");
}
} catch (ParseException e) {
e.printStackTrace();
}
Here if you want to avoid NullPointerException & ParseException checking:
public static boolean isAvailableForBooking() {
/* 10:00 AM */
final int OPEN_HOUR = 10; /* 0 - 23*/
final int OPEN_MINUTE = 0; /* 0 - 59*/
final int OPEN_SECOND = 0; /* 0 - 59*/
/* 07:00 PM */
final int CLOSED_HOUR = 19;
final int CLOSED_MINUTE = 0;
final int CLOSED_SECOND = 0;
Calendar openHour = Calendar.getInstance();
openHour.set(Calendar.HOUR_OF_DAY, OPEN_HOUR);
openHour.set(Calendar.MINUTE, OPEN_MINUTE);
openHour.set(Calendar.SECOND, OPEN_SECOND);
Calendar closedHour = Calendar.getInstance();
closedHour.set(Calendar.HOUR_OF_DAY, CLOSED_HOUR);
closedHour.set(Calendar.MINUTE, CLOSED_MINUTE);
closedHour.set(Calendar.SECOND, CLOSED_SECOND);
Calendar now = Calendar.getInstance();
return now.after(openHour) && now.before(closedHour);
}
tl;dr
Use modern java.time class, LocalTime.
( ! localTime.isBefore( LocalTime.of( 19 , 0 ) ) ) // Is not before the start… (meaning, is equal to or later than)
&& // …and…
localTime.isBefore( LocalTime.of( 7 , 0 ) ) ; // is before the end.
java.time
Never use Calendar or Date classes. These terrible classes were supplanted years ago by the modern java.time classes defined in JSR 310.
LocalTime start = LocalTime.of( 19 , 0 ) ; // 7 PM.
LocalTime end = LocalTime.of( 10 , 0 ) ; // 10 AM.
Determining the current time requires a time zone. For any given moment, the time of day, and the date, varies around the globe by zone.
If you want to use the JVM’s current default time zone, call ZoneId.systemDefault().
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
LocalTime localTime = LocalTime.now( z ) ;
Ask if the current time is equal to or later than the start and before the end. Tip: another way to ask “is equal to or later” is “is not before”.
boolean withinTimeRange = ( ! localTime.isBefore( start ) ) && localTime.isBefore( end ) ;
For early Android before 26, add the ThreeTenABP library to your project to get most of the java.time functionality with nearly the same API.
If you tried any code then please post it otherwise, You can check it by setting your current time and your service start time and end time on a Calendar Object and then get Date object from the calendar and can compare these dates.
String SERVICE_START_TIME="202-05-04 19:00:00";
String SERVICE_END_TIME="202-05-05 10:00:00";
public static boolean isValidTime() {
try {
Date time1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss",
Locale.getDefault()).parse(SERVICE_START_TIME);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
Date time2 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss",
Locale.getDefault()).parse(SERVICE_END_TIME);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
Date d = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss",
Locale.getDefault()).parse(getCurrentTime());
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date now = calendar3.getTime();
if (now.after(calendar1.getTime()) && now.before(calendar2.getTime())) {
return true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
You can get your system current time by using this function.
private static String getCurrentTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss",
Locale.getDefault());
return sdf.format(new Date()).toUpperCase();
}
Simpler solution would be to take time bounds in milliseconds. Then take your desired time in milliseconds and do the check lowerBound < desiredTime < upperBound.

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();

Add hours and Minutes to a certain time java

I have String initialTime= "10:30:00"
I am converting it into time like so:-
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Time time = new Time(date.getTime());
int initHour = time.getHours()
int initMind = time.getMinutes();
Further I have two values;
int hour, mins;
The hour value can be anything from 0-10;
mins value can be 0,15,30,45.
The user selects a time by selecting hour and mins. As soon as the user selects the values they should get added to the initialTimeand shown in finalTIme
So if:-
hour=0 and mins=15 then finalTIme=10:45:00
hour=0 and mins=35 then finalTIme=11:00:00
hour=0 and mins=45 then finalTIme=11:15:00
I tried doing something like:-
if(hour==0 && mins==0)
{
finalTime = initialTime;
}
else if(hour==0 && mins>0 && mins <30)
{
mins = initMins + mins
}
else if(hour==0 && mins>0 && mins >=30)
{
hours = hours+1;
mins = mins-60;
}
But I did not get the required output. HOw can I do it in a less complicated manner?
You can use java.util.Calendar class:
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hours);
cal.add(Calendar.MINUTE, minutes);
date = cal.getTime();
You might also consider the new Date API from JDK 8.

Subtract one Day from date when inside a time interval

I try to subtract one day when the time inside 0:00 am - 12:00 am.
ex: 2012-12-14 06:35 am => 2012-12-13
I have done a function and It's work. But my question is any other better code in this case? Much simpler and easy to understand.
public String getBatchDate() {
SimpleDateFormat timeFormatter = new SimpleDateFormat("H");
int currentTime = Integer.parseInt(timeFormatter.format(new Date()));
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
String Date = dateFormatter.format(new Date());
if ( 0 <= currentTime && currentTime <= 12){
try {
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(dateFormatter.parse(Date));
shiftDay.add(Calendar.DATE, -1);
Date = dateFormatter.format(shiftDay.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("BatchDate:", Date);
}
return Date;
}
THANKS,
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(new Date())
if(shiftDay.get(Calendar.HOUR_OF_DAY) <= 12){
shiftDay.add(Calendar.DATE, -1);
}
//your date format
Use the Calendar class to inspect and modify the Date.
Calendar cal = new GregorianCalendar(); // initializes calendar with current time
cal.setTime(date); // initializes the calender with the specified Date
Use cal.get(Calendar.HOUR_OF_DAY) to find out the hour within the day.
Use cal.add(Calendar.DATE, -1) to set the date one day back.
Use cal.getTime() to get a new Date instance of the time that was stored in the calendar.
As with nearly all questions with regard to Date / Time, try Joda Time
public String getBatchDate() {
DateTime current = DateTime.now();
if (current.getHourOfDay() <= 12)
current = current.minusDays(1);
String date = current.toString(ISODateTimeFormat.date());
Log.d("BatchDate:" + date);
return date;
}

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