How to get the time on the current android device? - java

I would like to get the current time on the android device with the app installed.
I want to be able to do something like this..
if(//time is pass noon){
//Do something
}
else{
//do something.
}
i want to tell if its am or pm.

Here is an example that should help you:
Calendar today = Calendar.getInstance();
Calendar expireDate = Calendar.getInstance();
expireDate.set(2011, Calendar.AUGUST, 12);
if (today.compareTo(expireDate) == 0 || today.compareTo(expireDate) == 1)
{
// expired - please purchase app
}
else
{
// do some stuff
}
To tell if it is AM or PM use:
int value = today.get(Calendar.AM_PM);
Or you could just get the hour:
int hour = today.get(Calendar.HOUR);
And then put that in an if statement:
if (hour > 12)
{
// do stuff
}
else
{
// do other stuff
}

You will get time here in 24 hrs format.So you can do as you like
final Calendar cld = Calendar.getInstance();
int time = cld.get(Calendar.HOUR_OF_DAY);
if(time>12){
//noon
}else{
//
}

Calendar now = Calendar.getInstance();
if (now.get(Calendar.AM_PM) == Calendar.AM) {
System.out.println("AM: Before noon");
} else { // == Calendar.PM
System.out.println("PM: After noon");
}

The current time is available with
new Date()
Parsing that for the time you can figure out if is AM or PM local time for the device.

Related

Check current time against specific times in Java and Android Studio

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

Convert time into milliseconds

I got the time from the launcher and time from system...I want to compare them and make sure that the difference is not more than 100milliseconds
public void test() throws InterruptedException {
/*
* Get the visible time from the launcher
*/
TextView onLauncherDisplay = (TextView) mNextUIMainActivity.findViewById(R.id.timeOfDay);
System.out.println("Launcher time: " + onLauncherDisplay.getText().toString());
/*
* Get the system time
*/
Calendar currentSystemTime = Calendar.getInstance();
currentSystemTime.setTime(new Date());
Calendar currentSystemTImeInMIlliseconds = Calendar.getInstance();
currentSystemTImeInMIlliseconds.seu
/*
* Convert time into 12-hour format
*/
SimpleDateFormat date = new SimpleDateFormat("h:mm aa");
Calendar onLauncherTime = Calendar.getInstance();
try {
onLauncherTime.setTime(date.parse(onLauncherDisplay.getText().toString()));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("System time: " + currentSystemTime.get(Calendar.HOUR) + ":" + currentSystemTime.get(Calendar.MINUTE));
Here i am comparing the time...hours and minutes but it is not perfect. I want to convert into milliseconds and the difference should not be more than 100 milliseconds
/*
* Compare the Launcher time with the System time
*/
if ((onLauncherTime.get(Calendar.HOUR) == currentSystemTime.get(Calendar.HOUR)) || (currentSystemTime.get(Calendar.HOUR) - onLauncherTime.get(Calendar.HOUR) == 1)) {
if (onLauncherTime.get(Calendar.MINUTE) == currentSystemTime.get(Calendar.MINUTE) || (currentSystemTime.get(Calendar.MINUTE) - onLauncherTime.get(Calendar.MINUTE) == 1)) {
System.out.println("Launcher time matches the On-System time!");
}
} else {
System.out.println("Launcher time does not matches the On-System time!!");
}
Use Calendar.getTimeInMillis():
if (currentSystemTime.getTimeInMillis() - onLauncherTime.getTimeInMillis() < 100)
//difference is less than 100 milliseconds
The Calendar class has a method getTimeInMillis that returns the unix epoc time value for the given calendar. That said, I don't fully understand what you're doing...

Checking time interval in java

I want some Java code that will tell me when school is open based on the current time.
When I call this method between 9AM and 6PM it should return "school is open", otherwise it should return "school is closed" after 6 pm and before 9 am.
public Calendar shopStartTime(String msg)
{
Calendar currentTime = Calendar.getInstance();
Calendar schoolTime = Calendar.getInstance();
Calendar schoolClosedTime = Calendar.getInstance();
schoolTime.set(Calendar.HOUR_OF_DAY, 9);
schoolTime.set(Calendar.MINUTE, 0);
schoolTime.set(Calendar.SECOND, 0);
schoolTime.set(Calendar.MILLISECOND, 0);
schoolClosedTime.set(Calendar.HOUR_OF_DAY, 18);
schoolClosedTime.set(Calendar.MINUTE, 0);
schoolClosedTime.set(Calendar.SECOND, 0);
schoolClosedTime.set(Calendar.MILLISECOND, 0);
if (schoolTime.compareTo(currentTime) <= 0 &&
(currentTime.compareTo(schoolClosedTime)>=0))
{
// check for time
Toast.makeText(getSherlockActivity(), "school is closed ",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getSherlockActivity(), " school is open",
Toast.LENGTH_SHORT).show();
}
return currentTime;
}
But the code is not working because it always returns the same result. How do I test if one time is between two other time of days?
Read the javadocs!
if (currentTime.after(schoolTime) && currentTime.before(schoolClosedTime)) {
// school is open
} else {
// school is closed
}
check if hour <9 && hour >18:
(or something else)
Calendar currentTime = Calendar.getInstance();
int hour = currentTime.get(Calendar.HOUR_OF_DAY);
you only need ONE calendar
Apart from Calendar that you have used , another simple approach would be :
private boolean inRange(Date now) throws ParseException {
final Date start = new SimpleDateFormat("HH.mm.ss").parse("09.00.00");
final Date end = new SimpleDateFormat("HH.mm.ss").parse("18.00.00");
return now.after(start)&& now.before(end);
}
You can use before() and after() of Calendar as well .

Calculate business days in java without saturdays, sunday and public holiday

i have a table in oracle where I saved the twelve public days in Mexico and I need to calculate a limit day since you registered
public Date calcularFechaLimite() {
try {
DiaFestivoDTO dia = new DiaFestivoDTO();
// Calendar fechaActual = Calendar.getInstance();
Calendar fechaL = Calendar.getInstance();
fechaL.add(Calendar.DATE, 3);
switch (fechaL.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SATURDAY:
fechaL.add(Calendar.DATE, 2);
break;
case Calendar.SUNDAY:
fechaL.add(Calendar.DATE, 2);
break;
case Calendar.MONDAY:
fechaL.add(Calendar.DATE, 2);
break;
case Calendar.TUESDAY:
fechaL.add(Calendar.DATE, 1);
default:
break;
}
dia.setFechaLimite(fechaL.getTime());
Integer numeroDiasFest = seleccionPagoBO.obtenerDiasFestivos(dia);
if (numeroDiasFest != 0) {
fechaL.add(Calendar.DATE, numeroDiasFest);
dia.setFechaLimite(fechaL.getTime());
}
fechaLimite = fechaL.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return fechaLimite;
}
This is what i have but March 28 and 29 are public days and it is not working, any idea??
Several issues:
You are not checking if the first 3 days you skip contain weekend days.
Also you are skipping strange amounts of days and skipping for weekdays as well (which are business days and therefore should not be skipped).
I assume the method DiaFestivoDTO.obtenerDiasFestivos() calculates the number of national holidays in a certain date range but what is the start date? Is it initialized to the current date when DiaFestivoDTO is created?
When there is a national holiday in your date range you increase the date range but never check if this new daterange includes new national holidays or weekend days.
If what you are trying to do is calculate a date '3 business days from now' here's roughly what I would do:
// get all the holidays as java.util.Date
DiaFestivoDTO dia = new DiaFestivoDTO();
List<Date> holidays = dia.getAllNationalHolidays();
// get the current date without the hours, minutes, seconds and millis
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// iterate over the dates from now and check if each day is a business day
int businessDayCounter = 0
while (businessDayCounter < 3) {
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY && !holidays.contains(cal.getTime())) {
businessDayCounter++;
}
cal.add(Calendar.DAY_OF_YEAR, 1);
}
Date threeBusinessDaysFromNow = cal.getTime();
For this to work I would advise you to add a new method 'getAllNationalHolidays' to list al the holidays because it is more efficient to store twelve dates in memory than to access the database multiple times to check for them.
If you cannot change/add database methods then you could do this
while (businessDayCounter < 3) {
// determine if this day is a holiday
DiaFestivoDTO dia = new DiaFestivoDTO();
dia.setFechaInitial(cal.getTime());
dia.setFechaLimite(cal.getTime());
boolean isHoliday = seleccionPagoBO.obtenerDiasFestivos(dia) > 0;
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY && !isHoliday) {
businessDayCounter++;
}
cal.add(Calendar.DAY_OF_YEAR, 1);
}
Here I assumed you can set the 'from' date in your DiaFestivoDTO using 'setFechaInitial' or something like that. But in this way you would be calling the database at least three times which is inefficient.

Android/Java: Time calculations

Im using the following code in my android app to get the current time
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
String time = dateFormatLocal.format(new Date());
I would like to know if theres an easy way to check timespans, for example if the clock is between 19:00 and 21:00. Thanks
There's nothing wrong with Chris's method, but here's another option:
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
if (hour >= 19 && hour < 21) {
System.out.println("WIN");
}
Then you can construct your string with:
String time = dateFormatLocal.format(now.getTime() );
I'll leave it to the next poster to point out that you can also use Joda-Time. :)
This might not be the most efficient solution (as I think you could probably do it with the Date objects) but what about
SimpleDateFormat df = new SimpleDateFormat("HH");
String hours = df.format(new Date());
Integer number = Integer.parseInt(hours);
if (numbers >= 19 && numbers <= 20){
//good
}else{
//not good
}

Categories