Set calendar to a value from a Date variable - java

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

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

Calculating date in mysql with java

I'm having trouble, finding out how to calculate or get the date from mysql (using java program) after 1 month of the initial saved date given below:
Date rDate = new Date();
java.sql.Date regDate = new java.sql.Date(rDate.getTime());
I am saving the date into a date column in mysql and I want to have another column which contains the date but one month ahead. In other words I have a registration date and I want to have an expiration date calculated automatically which allows only 1 month. Is it possible?
Grabbing the current date and set it into the Calendar format and add 1 to the month.
You can give this a try.
Date rDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(rDate);
cal.add(Calendar.MONTH, 1);
You can use Calendar class to manipulate date fields:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
Date futureDate = cal.getTime();

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

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

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

Java - Add specified number of Dates to a date

There are two date variables (Date1 and Date2) in the format YYYYMMDD. What i want is, according to the Date1 I want to set Date2 to the next month day one. For example :
If Date1 = 20111120 then
I want to set Date2 to 20111201
If Date1 = 20111210 then
The Date2 should be set to 20120101
No matter the Date1 the Date2 has to be set to next month day one. I cant figure this out how to do it.
Could anyone please help me on this issue.
use Calendar to move to the first of next month , SimpleDateFormat to parse from String to Date
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, 1);
DateFormat format = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
String date1 = "20111120";
calendar.setTime(format.parse(date1));
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, 1);
String date2 = format.format(calendar.getTime()); // date2 is "20111201"
Some caveats:
if you call this more than once, it might be a good idea to instantiate format and calendar only once.
SimpleDateFormat is not thread safe, so make sure to instantiate one SimpleDateFormat object for each threads (eg. using ThreadLocal)

Categories

Resources