I have an application that passes in java.util.Date. I want to check whether this date is within a specified time of day (e.g. between 10:30 & 11:30), I don't care about the date, just the time of day.
Can anyone show me a simple way to do this?
Thanks
This is what the Calendar class is for. Assuming date is your Date object:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
if (hour == 10 && minutes >= 30 || hour == 11 && minutes <= 30) {
...
}
Related
In my application I want to change background with Day/Night time.
My mean is I want check time if time is night set night background from drawable and when time is Day set day background from drawable.
Sorry for my bad question, I am an amateur and really need your help.
How can I do it in android?
You can use a code something like this, by specifying the hours you consider in morning and the hours you consider as night.
I considered the time from 06:00 - 18:00 as morning and 18:00 - 05:00 as night. Change it accordingly.
Calendar calendar = Calendar.getInstance();
int time = c.get(Calendar.HOUR_OF_DAY);
if(time >= 6 && time < 18){
image.setImageResource(R.drawable.morning);
}else if (time >= 18 && time < 6){
image.setImageResource(R.drawable.night);
}
EDIT
As suggested by #AxelH, it would be better to just specify either one of the time (morning or night only). The code would be something like:
Calendar calendar = Calendar.getInstance();
int time = c.get(Calendar.HOUR_OF_DAY);
if(time >= 6 && time < 18){
image.setImageResource(R.drawable.morning);
}else{
image.setImageResource(R.drawable.night);
}
Please try this:
Calendar time = Calendar.getInstance();
int gettime = time.get(Calendar.AM_PM);
if(Calendar.AM == gettime)
Log.d("AM"+now.get(Calendar.HOUR));
I have the following method that I took from the accepted answer this question Calculate number of weekdays between two dates in Java
public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
int workDays = 0;
//Return 0 if start and end are the same
if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
return 0;
}
if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do {
//excluding start date
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis()); //excluding end date
return workDays;
}
I pass to that function the first day and the last day of the current month I get the days like this:
Calendar firstDayOfMonth = Calendar.getInstance();
firstDayOfMonth .set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
Calendar lastDayOfMonth = Calendar.getInstance();
lastDayOfMonth .set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
and I pass the parameters to the function like this:
getWorkingDaysBetweenTwoDates(firstDayOfMonth.getTime(),
lastDayOfMonth.getTime());
I try the method and is returning 21 and we are in November of 2016 and this month have 22 working days not 21
I printed in console the parameters and these are the paramaters that I'm passing to the method
firstDayOfMonth.getTime() //equals to this Tue Nov 01 09:09:47 VET 2016
lastDayOfMonth.getTime() //equals to this Wed Nov 30 09:09:47 VET 2016
Indeed, to have the correct number :
do {
// excluding start date
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
}
should be replaced by :
do {
// excluding start date
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
startCal.add(Calendar.DAY_OF_MONTH, 1);
}
But I see another problem.
To give a correct result, the function supposes that there is a little time difference between the two date parameters :
For example, if you provide two dates (01-11-2016 and 30-11-2016) with last part of the datetime to 00:00:00:00, the days number returned will be 21.
If you create one date, after the second date, you will get 22.
The problem happens here :
while (startCal.getTimeInMillis() < endCal.getTimeInMillis());
Because even if it has only some milliseconds between startCal and endCal in the last iteration, it adds one undesirable day in the result.
To have a deterministic result, you should consider only day (and not time) in the transmitted dates :
Calendar firstDayOfMonth = Calendar.getInstance();
firstDayOfMonth.set(Calendar.MILLISECOND, 0);
firstDayOfMonth.set(Calendar.SECOND, 0);
firstDayOfMonth.set(Calendar.MINUTE, 0);
firstDayOfMonth.set(Calendar.HOUR, 0);
firstDayOfMonth.set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
Calendar lastDayOfMonth = Calendar.getInstance();
lastDayOfMonth.set(Calendar.MILLISECOND, 0);
lastDayOfMonth.set(Calendar.SECOND, 0);
lastDayOfMonth.set(Calendar.MINUTE, 0);
lastDayOfMonth.set(Calendar.HOUR, 0);
lastDayOfMonth.set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
int nbDays = getWorkingDaysBetweenTwoDates(firstDayOfMonth.getTime(),
lastDayOfMonth.getTime());
and use this condition in the loop :
while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());
This condition seems more natural since if the actual date is not after the last date (so before or equals), it should increment the counter for one additional day. Why exclude the last day ?
With Java 8 or JodaTime, it would be more simple and clean to set date values.
To avoid this kind of problem, I think that the getWorkingDaysBetweenTwoDates() method should reset to zero the time part of date parameters or use more specificDate objects (LocalDate for example) as parameters.
Replace startCal.getTimeInMillis() < endCal.getTimeInMillis()) with startCal.getTimeInMillis() <= endCal.getTimeInMillis()).
You current code act like end date not included in range.
I would like to know if the current time has passed 12 pm already. Can I do it in an if statement like:
if(timenow is already pass 12 pm){
**do code here**
}
Is there a java code or a method in joda time that can do that? All answers are appreciated. Thanks. :)
Calendar cal = Calendar.getInstance();
if (cal.get(Calendar.HOUR_OF_DAY) >= 12) {
...
}
JAVA
int hour = LocalDateTime.now().getHour();
JODATIME
DateTime dt = new DateTime(); // current time
int hour = dt.getHourOfDay(); // gets hour of day
and put the logic here
if(hour >= 12){
do code here
}
Here I want to display dates like
2013-01-01,
2013-01-02,
2013-01-03,
.
.
...etc
I can get total days in a month
private int getDaysInMonth(int month, int year) {
Calendar cal = Calendar.getInstance(); // or pick another time zone if necessary
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1); // 1st day of month
cal.set(Calendar.YEAR, year);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
Date startDate = cal.getTime();
int nextMonth = (month == Calendar.DECEMBER) ? Calendar.JANUARY : month + 1;
cal.set(Calendar.MONTH, nextMonth);
if (month == Calendar.DECEMBER) {
cal.set(Calendar.YEAR, year + 1);
}
Date endDate = cal.getTime();
// get the number of days by measuring the time between the first of this
// month, and the first of next month
return (int)((endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
}
Does anyone have an idea to help me?
If you only want to get the max number of days in a month you can do the following.
// Set day to one, add 1 month and subtract a day
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.get(Calendar.DAY_OF_MONTH);
If you actually want to print every day then you can just set the day of month to 1 and keep adding a day in a loop until the month changes.
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
int myMonth=cal.get(Calendar.MONTH);
while (myMonth==cal.get(Calendar.MONTH)) {
System.out.print(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 1);
}
Modern answer: Don’t use Calendar. Use java.time, the modern Java date and time API.
YearMonth ym = YearMonth.of(2013, Month.JANUARY);
LocalDate firstOfMonth = ym.atDay(1);
LocalDate firstOfFollowingMonth = ym.plusMonths(1).atDay(1);
firstOfMonth.datesUntil(firstOfFollowingMonth).forEach(System.out::println);
Output (abbreviated):
2013-01-01
2013-01-02
2013-01-03
…
2013-01-30
2013-01-31
datesUntil gives us a stream of dates until the specified end date exclusive, so when we give it the 1st of the following month, we get exactly all the dates of the month in question. In this example case up to and including January 31.
Link: Oracle tutorial: Date Time explaining how to use java.time.
This will give you all days of a month.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(df.format(cal.getTime()));
for (int i = 1; i < maxDay; i++) {
cal.set(Calendar.DAY_OF_MONTH, i + 1);
System.out.print(", " + df.format(cal.getTime()));
}
The first date is printed outside of loop for comma separated output.
A couple of comments...
Firstly, "... Calendar objects are particularly expensive to create." (J. Bloch, Effective Java, 2nd Ed.). If this is a method that you are going to be calling frequently, consider that you do not need to create a new Calendar object every time you call it.
Consider using a Calendar object held in a private static field that is initialized with a static initializer block. This presumes a single-threaded solution and would require synchronization in a concurrent environment. Otherwise, it really ought to be possible to reuse the same Calendar for your calculations.
Secondly, while you can find that greatest value for the DAY_OF_MONTH by iterating over the possible valid values, I think you can let the API do it for you. Consider using the getMaximum(DAY_OF_MONTH) or getGreatestMaximum(DAY_OF_MONTH) methods of the Calendar class.
Write a common method like that if you are using kotlin-
fun getAllDateOfMonth(year: Int, month: Month): List<LocalDate> {
val yearMonth= YearMonth.of(year, month)
val firstDayOfTheMonth = yearMonth.atDay(1)
val datesOfThisMonth = mutableListOf<LocalDate>()
for (daysNo in 0 until yearMonth.lengthOfMonth()){
datesOfThisMonth.add(firstDayOfTheMonth.plusDays(daysNo.toLong()))
}
return datesOfThisMonth
}
And call it like that -
getAllDateOfMonth(2021,Month.MAY):
I'm trying to create a method which is checking if "today" is between Monday and Friday. For this I get with this line 'int day = Calendar.DAY_OF_WEEK;' the actual day. After that I fill a ArrayList with the days (Monday, Tuesday, Wendsday, Thursday and Friday). Now when I check if the actual day is in my ArrayList, i set boolean DAY = true else i set boolean DAY = false. I tryed the Method today and yesterday, but it allways sets the boolean to false.
What do I need to change that my code works? You'll find the code down here.
Code
int day = Calendar.DAY_OF_WEEK;
ArrayList<Integer> daylist = new ArrayList<Integer>();
daylist.add(Calendar.MONDAY);
daylist.add(Calendar.TUESDAY);
daylist.add(Calendar.WEDNESDAY);
daylist.add(Calendar.THURSDAY);
daylist.add(Calendar.FRIDAY);
if (daylist.contains(day)){
DAY = true;
}else{
DAY = false;
}
Wow, that's like trying to kill a mosquito with a thermo-nuclear warhead :-)
Java guarantees (in 1.5) (unchanged up to 1.8 at least) that the values of SUNDAY through SATURDAY are contiguous (1 through 7) so it's a simple matter of checking a range.
However, DAY_OF_WEEK is not the day of the week, it's a field number (with the value 7) to be passed to the getter to retrieve the day of the week. The only time Calendar.DAY_OF_WEEK itself will match an actual day will be on Saturdays.
You can use code such as:
Calendar myDate = Calendar.getInstance(); // set this up however you need it.
int dow = myDate.get (Calendar.DAY_OF_WEEK);
boolean isWeekday = ((dow >= Calendar.MONDAY) && (dow <= Calendar.FRIDAY));
Following this, isWeekday will be true if and only if the day from myDate was Monday through Friday inclusive.
int day = Calendar.DAY_OF_WEEK; should instead be
Calendar cal; // The calendar object
....your other code for getting the date goes here....
int day = cal.get(Calendar.DAY_OF_WEEK);
Your current code just gets the value of the constant Calendar.DAY_OF_WEEK.
This should do the trick for you i assume.
int day = cal.get(Calendar.DAY_OF_WEEK);
if (day >= Calendar.MONDAY && day <= Calendar.FRIDAY){
DAY = true;
}else{
DAY = false;
}
int day = Calendar.DAY_OF_WEEK;
The logic is broken right here. DAY_OF_WEEK is a constant identifying which type of data we need to retrieve from a Calendar instance.
The simplest solution to your problem (since Calendar.FRIDAY > ... > Calendar.MONDAY) is
Calendar now = Calendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
if (day >= Calendar.MONDAY && day <= Calendar.FRIDAY)
// do something
First Calendar.DAY_OF_WEEK is an integer field will always gives you 7. You need to create an instance of a Calendar like Calendar cal = Calendar.getInstance(); By default it gives you the current date in current timezone.
Then you can call cal.get(Calendar.DAY_OF_WEEK); which will give you any day between Sunday and Sat'day
Now you can check something like this
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
System.out.println("Weekend");
} else {
System.out.println("Weekday");
}
You can apply this logic to your problem!!