java - Start Date of Last Month [duplicate] - java

This question already has answers here:
How to get the first date and last date of the previous month? (Java)
(9 answers)
Closed 7 years ago.
I want to calculate the start date of the last month. I have referred this post and I have written the snippet as follows:
Calendar calendar = getCalendar(new Date());
calendar.set(Calendar.DAY_OF_MONTH-1,
calendar.getActualMinimum(DAY_OF_MONTH));
calendar = getTimeToBeginningOfDay(calendar);
return calendar.getTime();
With this I'm able to get the Date before the end of the last month. Help me get the start date of Any help would be appreciated.

You should never do math on field constants such as Calendar.DAY_OF_MONTH. What you want to do is:
Calendar calendar = getCalendar(new Date());
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar = getTimeToBeginningOfDay(calendar);
return calendar.getTime();

You may get what you expect with :
Calendar c = Calendar.getInstance();
// substract one month
c.add(Calendar.MONTH, -1);
// get to the lowest day of that month
c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
// lowest possible time in that day
c.set(Calendar.HOUR_OF_DAY, c.getActualMinimum(Calendar.HOUR_OF_DAY));
c.set(Calendar.MINUTE, c.getActualMinimum(Calendar.MINUTE));
c.set(Calendar.SECOND, c.getActualMinimum(Calendar.SECOND));

If you just want the first day of the previous month, then this should do it.
Calendar instance = Calendar.getInstance();
instance.add(Calendar.MONTH, -1);
instance.set(Calendar.DAY_OF_MONTH, 1);
System.out.println(instance.getTime());
If you need to to clear out the time component, then use getTimeToBeginningOfDay() mentioned in the post to achieve this.

Related

Setting the year in Calendar [duplicate]

This question already has answers here:
java.util.Date is generating a wrong date?
(3 answers)
Closed 6 years ago.
I have the following piece of code.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/YYYY HH:mm");
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2016);
cal.set(Calendar.MONTH, 11);
cal.set(Calendar.DAY_OF_MONTH, 31);
cal.set(Calendar.HOUR_OF_DAY, 22);
Date start = cal.getTime();
System.out.println(dateFormat.format(start));
cal.set(Calendar.YEAR, 2017);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 5);
Date end = cal.getTime();
System.out.println(dateFormat.format(end));
It prints:
31/12/2016 22:00
01/01/2016 05:00
I expect that the year of the second date is 2017. What is going on? I'm using Java 1.7.
The correct date format should be dd/MM/yyyy HH:mm, not dd/MM/YYYY HH:mm, note the lower case y.
With that it works correctly.
From the docs:
y Year
Y Week year
Explanation of the difference between year and week year (from here):
A week year is a year where all the weeks in the year are whole weeks.
[...] Basically, this guarantees that a program working on a week's
data will not transition between years. [...] this also means that the beginning of the year may not start on the first of January.
This is working fine with the following dataFormat.
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm");

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

JAVA how to take a Date and see the day, month, and year? [duplicate]

This question already has answers here:
Adding a number to the day or month or year in a date [duplicate]
(4 answers)
Closed 8 years ago.
I have a assignment for a class where we take in a date then see if the date given is valid. If it is we then add a day onto it. Where I am having trouble is after I check that the date is valid it is saved to
Date appointment = new Date();
appointment = new Date(month, day, year);
Date.advanceDate(appointment);
in a different file called Date.java
public static void advanceDate(Date aDate){
//here is where I need to read the date in aDate
}
After searching online through the Java api I haven't been able to find a way to add a day onto appointment or get the day, month, and year from appointment add a day to that and then save it as a new Date
what I have tried is doing after looking at http://docs.oracle.com/javase/8/docs/api/java/util/Date.html
aDate.getDay();
but eclipse tells me "the method getDate()is undefined for the type Data
aDate.toString();
this doesn't return the month date and year it returns its location in memery
every solution I've found online uses Calender which seems to have replaced Date
I believe you are looking for a Calendar and a DateFormat,
int year = 2015;
int month = Calendar.FEBRUARY; // <-- this is actually a 1.
int date = 8;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
cal.add(Calendar.DAY_OF_MONTH, 1);
System.out.println(df.format(cal.getTime()));
Output is
2015-02-09
1FEBRUARY.

how to add days to date in java using simpledateformat and store output in string [duplicate]

This question already has answers here:
Adding days to a date in Java [duplicate]
(6 answers)
Closed 8 years ago.
Below is the code which generates the output as "9/2/2014"
public static void main (String[]args) throws ParseException
{
java.util.Date d = new Date();
SimpleDateFormat sd = new SimpleDateFormat("M/d/yyyy");
System.out.println(sd.format(d));
}
Now i need to add some n no of days and i wanted to get the output as 9/12/2014
please help me ...
If you want add month, or days to your date, use something like that:
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
to add month use Calendar.Month
Calendar has methods for date manipulations. First create Calendar instance and set date to it
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Then you can use calendar instance to add days like
calendar.add(Calendar.DATE,10);
to get date from calendar, use
System.out.println(calendar.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()));

Categories

Resources