Alternate method for setHours() of java.util.Date? - java

What is an alternate method for setHours() of java.util.Date as it is deprecated. To my date variable, I want to set certain hours but I don't want to use the deprecated method setHours().

Try this:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
Date date = cal.getTime();
If you have a Date object already, you can use cal.setTime(date) to initialize calendar with the given date.
JavaDoc for Calendar.HOUR_OF_DAY
Field number for get and set indicating the hour of the day.
HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM
the HOUR_OF_DAY is 22.

Instead of using Date class functions which are deprecated you can use Calendar class.
Calendar calendar=Calendar.getInstance();
calendar.setTime(YOUR_DATE_OBJECT);
calendar.set(Calendar.HOUR_OF_DAY, hour);
Date date=calendar.getTime();

This is how you can save/set the DATE parameters using Java Calendar object methods.
Calendar now = Calendar.getInstance();
now.setTime(YOUR_DATE);
now.set(Calendar.HOUR_OF_DAY, 6);
YOUR_DATE = now.getTime();

Related

java.util.date getActualMaximum(Calendar.DAY_OF_MONTH) [duplicate]

I am having issues with the calculation of when the next Last Day of the Month is for a notification which is scheduled to be sent.
Here is my code:
RecurrenceFrequency recurrenceFrequency = notification.getRecurrenceFrequency();
Calendar nextNotifTime = Calendar.getInstance();
This is the line causing issues I believe:
nextNotifTime.add(recurrenceFrequency.getRecurrencePeriod(),
recurrenceFrequency.getRecurrenceOffset());
How can I use the Calendar to properly set the last day of the next month for the notification?
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
This returns actual maximum for current month. For example it is February of leap year now, so it returns 29 as int.
java.time.temporal.TemporalAdjusters.lastDayOfMonth()
Using the java.time library built into Java 8, you can use the TemporalAdjuster interface. We find an implementation ready for use in the TemporalAdjusters utility class: lastDayOfMonth.
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
LocalDate now = LocalDate.now(); //2015-11-23
LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth()); //2015-11-30
If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like
lastDay.atStartOfDay(); //2015-11-30T00:00
And to get last day as Date object:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
Date lastDayOfMonth = cal.getTime();
You can set the calendar to the first of next month and then subtract a day.
Calendar nextNotifTime = Calendar.getInstance();
nextNotifTime.add(Calendar.MONTH, 1);
nextNotifTime.set(Calendar.DATE, 1);
nextNotifTime.add(Calendar.DATE, -1);
After running this code nextNotifTime will be set to the last day of the current month. Keep in mind if today is the last day of the month the net effect of this code is that the Calendar object remains unchanged.
Following will always give proper results:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, ANY_MONTH);
cal.set(Calendar.YEAR, ANY_YEAR);
cal.set(Calendar.DAY_OF_MONTH, 1);// This is necessary to get proper results
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
cal.getTime();
You can also use YearMonth.
Like:
YearMonth.of(2019,7).atEndOfMonth()
YearMonth.of(2019,7).atDay(1)
See
https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#atEndOfMonth--
Using the latest java.time library here is the best solution:
LocalDate date = LocalDate.now();
LocalDate endOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
Alternatively, you can do:
LocalDate endOfMonth = date.withDayOfMonth(date.lengthOfMonth());
Look at the getActualMaximum(int field) method of the Calendar object.
If you set your Calendar object to be in the month for which you are seeking the last date, then getActualMaximum(Calendar.DAY_OF_MONTH) will give you the last day.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse("11/02/2016");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("First Day Of Month : " + calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
System.out.println("Last Day of Month : " + calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Kotlin date extension implementation using java.util.Calendar
fun Date.toEndOfMonth(): Date {
return Calendar.getInstance().apply {
time = this#toEndOfMonth
}.toEndOfMonth().time
}
fun Calendar.toEndOfMonth(): Calendar {
set(Calendar.DAY_OF_MONTH, getActualMaximum(Calendar.DAY_OF_MONTH))
return this
}
You can call toEndOfMonth function on each Date object like Date().toEndOfMonth()

Mixing java.util.date and a java.sql.Time in Java

I want to construct a date based in a java.util.date and a java.sql.Time, so I code this:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY,time.getHours());
cal.set(Calendar.MINUTE, time.getMinutes());
cal.set(Calendar.SECOND, time.getSeconds());
cal.getTime();
It works but ime.getHours(), time.getMinutes(), time.getSeconds() appears as deprecated, how can we make it with a no deprecated method ????
By the looks of what you're doing, I think this is what you want:
Calendar mergedCal = Calendar.getInstance();
mergedCal.setTime(date);
Calendar sqlCal = Calendar.getInstance();
sqlCal.setTime(time.getTime());
mergedCal.set(Calendar.HOUR_OF_DAY, sqlCal.get(Calendar.HOUR_OF_DAY));
mergedCal.set(Calendar.MINUTE, sqlCal.get(Calendar.MINUTE));
mergedCal.set(Calendar.SECOND, sqlCal.get(Calendar.SECOND));
mergedCal.getTime();
At the end of this computation, mergedCal will use the date from date and the time-of-day from time.

Set calendar to a value from a Date variable

I have a variable date1 which stores a date. I need to get the year from that. So, I want to instantiate a calendar and set its date to the one from date1. Then, I can use getYear().
How do I set the calendar
Date date1; //I set its value from database.
Calendar ca1 = Calendar.getInstance();
ca1.set(date1); // doesn't work
Is there a workaround ?
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int year= cal.get(Calendar.YEAR);// Here is your desired year
Use setTime :
Sets this Calendar's time with the given Date.
ca1.setTime(date1);
You should use:
ca1.setTime(date1);
Calendar ca1 = Calendar.getInstance();
ca1.setTime(date1);
doing only Date date1; will not work because here only reference is created
you have to do Date date1=new Date();
Suppose dbDate is the date you are getting from Database
Date date1=new Date(dbDate);
then do
Calendar ca1 = Calendar.getInstance();
ca1.setTime(date1);

How to set a Java Date object's value to yesterday? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get yesterday's date using Date
What is an elegant way set to a Java Date object's value to yesterday?
With JodaTime
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minus(Period.days(1));
System.out.printf("Today is : %s, Yesterday : %s", today.toString("yyyy-MM-dd"), yesterday.toString("yyyy-MM-dd"));
Do you mean to go back 24 hours in time.
Date date = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000L);
or to go back one day at the time same time (this can be 23 or 25 hours depending on daylight savings)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
These are not exactly the same due to daylight saving.
Convert the Date to a Calendar object and "roll" it back a single day. Something like this helper method take from here:
public static void addDays(Date d, int days)
{
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, days);
d.setTime(c.getTime().getTime());
}
For your specific case, just pass in days as -1 and you should be done. Just make sure you take into consideration the timezone/locale if doing extensive date specific manipulations.
you can try the follwing code:
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
As many people have already said use Calendar rather than date.
If you find you really want to use dates:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
cal.getTime();//returns a Date object
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DAY_OF_MONTH, -1);
cal1.getTime();//returns a Date object
I hope this helps.
tomred
You can try the following example to set it to previous date.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today's date is " +dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));

Android Format calendar to output time

I am using the below code to set an alarm. I would like to output what the time for this would be. I don't know if I going about this the wrong way. If I output the variable cal it has a long string of information. How do I extract only the hour and minutes?
Calendar cal = Calendar.getInstance();
// add 5 minutes to the calendar object
cal.add(Calendar.MINUTE, 464);
You can use the static constants as m0skit0 says, or use SimpleDateFormat. Here's some code to show both methods:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 464);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
System.out.println(sdf.format(cal.getTime()));
System.out.println(cal.get(Calendar.HOUR)+":"+cal.get(Calendar.MINUTE));
outputs:
05:31
5:31
Use the get() method on your Calendar object, and use Calendar static constants for the needed field (hour, minute, etc...).
For example:
cal.get(Calendar.Minute);

Categories

Resources