Related
I have to use the Java Date class for this problem (it interfaces with something out of my control).
How do I get the start and end date of a year and then iterate through each date?
java.time
Using java.time library built into Java 8 and later. Specifically the LocalDate and TemporalAdjusters classes.
import java.time.LocalDate
import static java.time.temporal.TemporalAdjusters.firstDayOfYear
import static java.time.temporal.TemporalAdjusters.lastDayOfYear
LocalDate now = LocalDate.now(); // 2015-11-23
LocalDate firstDay = now.with(firstDayOfYear()); // 2015-01-01
LocalDate lastDay = now.with(lastDayOfYear()); // 2015-12-31
If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like
lastDay.atStartOfDay(); // 2015-12-31T00:00
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, 1);
Date start = cal.getTime();
//set date to last day of 2014
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 11); // 11 = december
cal.set(Calendar.DAY_OF_MONTH, 31); // new years eve
Date end = cal.getTime();
//Iterate through the two dates
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
gcal.add(Calendar.DAY_OF_YEAR, 1);
//Do Something ...
}
// suppose that I have the following variable as input
int year=2011;
Calendar calendarStart=Calendar.getInstance();
calendarStart.set(Calendar.YEAR,year);
calendarStart.set(Calendar.MONTH,0);
calendarStart.set(Calendar.DAY_OF_MONTH,1);
// returning the first date
Date startDate=calendarStart.getTime();
Calendar calendarEnd=Calendar.getInstance();
calendarEnd.set(Calendar.YEAR,year);
calendarEnd.set(Calendar.MONTH,11);
calendarEnd.set(Calendar.DAY_OF_MONTH,31);
// returning the last date
Date endDate=calendarEnd.getTime();
To iterate, you should use the calendar object and increment the day_of_month variable
Hope that it can help
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_YEAR, 1);
System.out.println(cal.getTime().toString());
cal.set(Calendar.DAY_OF_YEAR, 366); // for leap years
System.out.println(cal.getTime().toString());
An improvement over Srini's answer.
Determine the last date of the year using Calendar.getActualMaximum.
Calendar cal = Calendar.getInstance();
calDate.set(Calendar.DAY_OF_YEAR, 1);
Date yearStartDate = calDate.getTime();
calDate.set(Calendar.DAY_OF_YEAR, calDate.getActualMaximum(Calendar.DAY_OF_YEAR));
Date yearEndDate = calDate.getTime();
If you are looking for a one-line-expression, I usually use this:
new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(new java.util.Date().getYear())+"-01-01")
I assume that you have Date class instance and you need to find first date and last date of the current year in terms of Date class instance. You can use the Calendar class for this. Construct Calendar instance using provided date class instance. Set the MONTH and DAY_OF_MONTH field to 0 and 1 respectively, then use getTime() method which will return Date class instance representing first day of year. You can use same technique to find end of year.
Date date = new Date();
System.out.println("date: "+date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println("cal:"+cal.getTime());
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("cal new: "+cal.getTime());
Update: The Joda-Time library is now in maintenance mode with its team advising migration to the java.time classes. See the correct java.time Answer by Przemek.
Time Zone
The other Answers ignore the crucial issue of time zone.
Joda-Time
Avoid doing date-time work with the notoriously troublesome java.util.Date class. Instead use either Joda-Time or java.time. Convert to j.u.Date objects as needed for interoperability.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
int year = 2015 ;
DateTime firstOfYear = new DateTime( year , DateTimeConstants.JANUARY , 1 , 0 , 0 , zone ) ;
DateTime firstOfNextYear = firstOfYear.plusYears( 1 ) ;
DateTime firstMomentOfLastDayOfYear = firstOfNextYear.minusDays( 1 ) ;
Convert To java.util.Date
Convert to j.u.Date as needed.
java.util.Date d = firstOfYear.toDate() ;
You can use Jodatime as shown in this thread Java Joda Time - Implement a Date range iterator
Also, you can use gregorian calendar and move one day at a time, as shown here. I need a cycle which iterates through dates interval
PS. Piece of advice: search it first.
You can use the apache commons-lang project which has a DateUtils class.
They provide an iterator which you can give the Date object.
But I highly suggest using the Calendar class as suggested by the other answers.
First and Last day of Year
import java.util.Calendar
import java.text.SimpleDateFormat
val parsedDateInt = new SimpleDateFormat("yyyy-MM-dd")
val cal2 = Calendar.getInstance()
cal2.add(Calendar.MONTH, -(cal2.get(Calendar.MONTH)))
cal2.set(Calendar.DATE, 1)
val firstDayOfYear = parsedDateInt.format(cal2.getTime)
cal2.add(Calendar.MONTH, (11-(cal2.get(Calendar.MONTH))))
cal2.set(Calendar.DATE, cal2.getActualMaximum(Calendar.DAY_OF_MONTH))
val lastDayOfYear = parsedDateInt.format(cal2.getTime)
val instance = Calendar.getInstance()
instance.add(Calendar.YEAR,-1)
val prevYear = SimpleDateFormat("yyyy").format(DateTime(instance.timeInMillis).toDate())
val firstDayPreviousYear = DateTime(prevYear.toInt(), 1, 1, 0, 0, 0, 0)
val lastDayPreviousYear = DateTime(prevYear.toInt(), 12, 31, 0, 0, 0, 0)
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
gcal.add(Calendar.DAY_OF_YEAR, 1);
//Do Something ...
}
The GregorianCalendar creation here is pointless. In fact, going through Calendar.java source code shows that Calendar.getInstance() already gives a GregorianCalendar instance.
Regards,
Nicolas
Calendar cal = Calendar.getInstance();//getting the instance of the Calendar using the factory method
we have a get() method to get the specified field of the calendar i.e year
int year=cal.get(Calendar.YEAR);//for example we get 2013 here
cal.set(year, 0, 1); setting the date using the set method that all parameters like year ,month and day
Here we have given the month as 0 i.e Jan as the month start 0 - 11 and day as 1 as the days starts from 1 to30.
Date firstdate=cal.getTime();//here we will get the first day of the year
cal.set(year,11,31);//same way as the above we set the end date of the year
Date lastdate=cal.getTime();//here we will get the last day of the year
System.out.print("the firstdate and lastdate here\n");
java.time.YearMonth
How to Get First Date and Last Date For Specific Year and Month.
Here is code using YearMonth Class.
YearMonth is a final class in java.time package, introduced in Java 8.
public static void main(String[] args) {
int year = 2021; // you can pass any value of year Like 2020,2021...
int month = 6; // you can pass any value of month Like 1,2,3...
YearMonth yearMonth = YearMonth.of( year, month );
LocalDate firstOfMonth = yearMonth.atDay( 1 );
LocalDate lastOfMonth = yearMonth.atEndOfMonth();
System.out.println(firstOfMonth);
System.out.println(lastOfMonth);
}
See this code run live at IdeOne.com.
2021-06-01
2021-06-30
I want to select Sunday before first Monday of the passed month.
That Sunday may be in the same month or the previous month but I want date of Sunday. I tried below logic for getting Sunday, it works for the current month but if I try passing some another month like Nov-2017 then again I have to change MONDAY-2 to MONDAY-3. So this is not the correct way. So how can I achieve this ?
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
c.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY - 2);
System.out.println("Date " + c.getTime());
I want to pass date to the code. So how can i do it ? like if I have date saved in variable then according to the input provided by that variable it should calculate the logic and provide the output
#Test
public void testDate() throws ParseException {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
Date d = fmt.parse("01-Nov-2017");
System.out.println(d);
Calendar c = Calendar.getInstance();
c.setTime(d);
getSundayBefore1thMondayOfMonth(c);
}
public void getSundayBefore1thMondayOfMonth(Calendar c) {
c.set(Calendar.DAY_OF_MONTH, 1);
int wd = c.get(Calendar.DAY_OF_WEEK);
if (wd > Calendar.MONDAY ) {
c.add(Calendar.DAY_OF_MONTH, 7);
}
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(c.getTime());
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(c.getTime());
}
Wed Nov 01 00:00:00 CST 2017
Mon Nov 06 00:00:00 CST 2017
Sun Nov 05 00:00:00 CST 2017
If you are using Java 8, Then you can use java.time library and you can just use :
LocalDate firstMondayOfMonth = LocalDate.now().with(
TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)
);// This return 2018-01-01
LocalDate sunday = firstMondayOfMonth.minusDays(1);//This return 2017-12-31
To test with November 2017 you can use LocalDate.of instead LocalDate.now() like this :
LocalDate firstMondayOfMonth = LocalDate.of(2017, Month.NOVEMBER, 1).with(
TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)
);// This return 2017-11-06
LocalDate firstSunday = firstMondayOfMonth.minusDays(1);// This return 2017-11-05
tl;dr
YearMonth
.now() // Current year-month. Tip: Better to pass the optional time zone, as shown further down in this Answer.
.atDay( 1 ) // First of the current month.
.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) // Move from first day of month to the following Monday, or stay on the first if it already a Monday.
.minusDays( 1 ) // Move back one day from Monday to get a Sunday. May be in current month or in previous month.
java.time
You are using troublesome old date-date classes that are now legacy, supplanted by the java.time classes.
Determining the current month means determining the current date. Determining the current date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
The YearMonth class represent the entire month.
YearMonth currentYearMonth = YearMonth.now( z ) ;
From that we can get the first of the month.
LocalDate firstOfMonth = currentYearMonth.atDay( 1 ) ;
We can move to a certain day of the week by calling on a TemporalAdjuster.
LocalDate firstMondayOfMonth = firstOfMonth.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) ;
LocalDate sundayBeforeFirstMondayOfMonth = firstMondayOfMonth.with( TemporalAdjusters.previous( DayOfWeek.SUNDAY ) ) ;
Logically, that last line could be replaced with .minusDays( 1 ) as we know the previous Sunday immediately precedes our Monday by definition.
In the code below, first we get the first monday in the month. Then we just subtract 1 day.
// input
int year = 2017;
int month = Calendar.NOVEMBER;
// get first monday of the month
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
System.out.println("Date " + c.getTime());
// subtract 1
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println("Date " + c.getTime());
Try this:
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
calendar.add(Calendar.DATE, -1);
System.out.println(calendar.getTime());
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek( Calendar.MONDAY); //Monday is first day of a week
c.setMinimalDaysInFirstWeek( 1); //first week of month is the week that has at least one day in this month
//c.setMinimalDaysInFirstWeek( 7); //first week of month must be a full week
c.set(Calendar.WEEK_OF_MONTH, 1); //move to first week of month
System.out.println("Date " + c.getTime());
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); //move to Monday
System.out.println("Date " + c.getTime());
c.add( Calendar.DAY_OF_MONTH, -1); //go back one day
System.out.println("Date " + c.getTime());
Choose one of the c.setMinimalDaysInFirstWeek() method depending on what the first week of month means to you.
In Java 8, you can use the below code:
public static void getSundayBeforeFirstMondayOfMonth(LocalDate date){
date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)).minusDays(1);
}
And, call the above method like below as per the requirement:
public static void callerMethod(){
// Call with Current Date
getSundayBeforeFirstMondayOfMonth(LocalDate.now());
//Call with Custom Date
LocalDate customDate = LocalDate.parse("27-11-2017", DateTimeFormatter.ofPattern("DD-MM-YYYY"));
getSundayBeforeFirstMondayOfMonth(customDate);
}
I have a problem resetting hours in Java. For a given date I want to set the hours to 00:00:00.
This is my code :
/**
* Resets milliseconds, seconds, minutes and hours from the provided date
*
* #param date
* #return
*/
public static Date trim(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
return calendar.getTime();
}
The problem is that sometimes the time is 12:00:00 and sometimes it is 00:00:00 and when I query the database for an entity that was saved on 07.02.2013 00:00:00 and the actual entity time, that is stored, is 12:00:00 the query fails.
I know that 12:00:00 == 00:00:00!
I am using AppEngine. Is this an appengine bug, problem or some other issue? Or does it depend on something else?
Use another constant instead of Calendar.HOUR, use Calendar.HOUR_OF_DAY.
calendar.set(Calendar.HOUR_OF_DAY, 0);
Calendar.HOUR uses 0-11 (for use with AM/PM), and Calendar.HOUR_OF_DAY uses 0-23.
To quote the Javadocs:
public static final int HOUR
Field number for get and set indicating
the hour of the morning or afternoon. HOUR is used for the 12-hour
clock (0 - 11). Noon and midnight are represented by 0, not by 12.
E.g., at 10:04:15.250 PM the HOUR is 10.
and
public static final int 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.
Testing ("now" is currently c. 14:55 on July 23, 2013 Pacific Daylight Time):
public class Main
{
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
System.out.println(sdf.format(now.getTime()));
now.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(now.getTime()));
}
}
Output:
$ javac Main.java
$ java Main
2013-07-23 12:00:00
2013-07-23 00:00:00
java.time
Using the java.time framework built into Java 8 and later. See Tutorial.
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now(); # 2015-11-19T19:42:19.224
# start of a day
now.with(LocalTime.MIN); # 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); # 2015-11-19T00:00
If you do not need time-of-day (hour, minute, second etc. parts) consider using LocalDate class.
LocalDate.now(); # 2015-11-19
Here are couple of utility functions I use to do just this.
/**
* sets all the time related fields to ZERO!
*
* #param date
*
* #return Date with hours, minutes, seconds and ms set to ZERO!
*/
public static Date zeroTime( final Date date )
{
return DateTimeUtil.setTime( date, 0, 0, 0, 0 );
}
/**
* Set the time of the given Date
*
* #param date
* #param hourOfDay
* #param minute
* #param second
* #param ms
*
* #return new instance of java.util.Date with the time set
*/
public static Date setTime( final Date date, final int hourOfDay, final int minute, final int second, final int ms )
{
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime( date );
gc.set( Calendar.HOUR_OF_DAY, hourOfDay );
gc.set( Calendar.MINUTE, minute );
gc.set( Calendar.SECOND, second );
gc.set( Calendar.MILLISECOND, ms );
return gc.getTime();
}
One more JAVA 8 way:
LocalDateTime localDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
But it's a lot more useful to edit the date that already exists.
See the below code:
String datePattern24Hrs = "yyyy-MM-dd HH:mm:ss";
String datePattern12Hrs = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat simpleDateFormat24Hrs = new SimpleDateFormat(datePattern24Hrs);
SimpleDateFormat simpleDateFormat12Hrs = new SimpleDateFormat(datePattern12Hrs);
Date dateNow = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateNow);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date dateTime = calendar.getTime();
String dateTimeIn24Hrs = simpleDateFormat24Hrs.format(dateTime);
String dateTimeIn12Hrs = simpleDateFormat12Hrs.format(dateTime);
System.out.println("DateTime in 24Hrs: ".concat(dateTimeIn24Hrs));
System.out.println("DateTime in 12Hrs: ".concat(dateTimeIn12Hrs));
The expected output is as below:
DateTime in 24Hrs: 2021-06-29 00:00:00
DateTime in 12Hrs: 2021-06-29 12:00:00
I hope it helps with the answer you are looking for.
You would better to primarily set time zone to the DateFormat component like this:
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Then you can get "00:00:00" time by passing 0 milliseconds to formatter:
String time = dateFormat.format(0);
or you can create Date object:
Date date = new Date(0); // also pass milliseconds
String time = dateFormat.foramt(date);
or you be able to have more possibilities using Calendar component but you should also set timezone as GMT to calendar instance:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 37);
calendar.set(Calendar.SECOND, 27);
dateFormat.format(calendar.getTime());
tl;dr
myJavaUtilDate // The terrible `java.util.Date` class is now legacy. Use *java.time* instead.
.toInstant() // Convert this moment in UTC from the legacy class `Date` to the modern class `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
.toLocalDate() // Extract the date-only portion.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) ) // Determine the first moment of that date in that zone. The day does *not* always start at 00:00:00.
java.time
You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
Date ➙ Instant
A java.util.Date represent a moment in UTC. Its replacement is Instant. Call the new conversion methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Time zone
Specify the time zone in which you want your new time-of-day to make sense.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime
Apply the ZoneId to the Instant to get a ZonedDateTime. Same moment, same point on the timeline, but different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Changing time-of-day
You asked to change the time-of-day. Apply a LocalTime to change all the time-of-day parts: hour, minute, second, fractional second. A new ZonedDateTime is instantiated, with values based on the original. The java.time classes use this immutable objects pattern to provide thread-safety.
LocalTime lt = LocalTime.of( 15 , 30 ) ; // 3:30 PM.
ZonedDateTime zdtAtThreeThirty = zdt.with( lt ) ;
First moment of day
But you asked specifically for 00:00. So apparently you want the first moment of the day. Beware: some days in some zones do not start at 00:00:00. They may start at another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).
Let java.time determine the first moment. Extract the date-only portion. Then pass the time zone to get first moment.
LocalDate ld = zdt.toLocalDate() ;
ZonedDateTime zdtFirstMomentOfDay = ld.atStartOfDay( z ) ;
Adjust to UTC
If you need to go back to UTC, extract an Instant.
Instant instant = zdtFirstMomentOfDay.toInstant() ;
Instant ➙ Date
If you need a java.util.Date to interoperate with old code not yet updated to java.time, convert.
java.util.Date d = java.util.Date.from( instant ) ;
As Java8 add new Date functions, we can do this easily.
// If you have instant, then:
Instant instant1 = Instant.now();
Instant day1 = instant1.truncatedTo(ChronoUnit.DAYS);
System.out.println(day1); //2019-01-14T00:00:00Z
// If you have Date, then:
Date date = new Date();
Instant instant2 = date.toInstant();
Instant day2 = instant2.truncatedTo(ChronoUnit.DAYS);
System.out.println(day2); //2019-01-14T00:00:00Z
// If you have LocalDateTime, then:
LocalDateTime dateTime = LocalDateTime.now();
LocalDateTime day3 = dateTime.truncatedTo(ChronoUnit.DAYS);
System.out.println(day3); //2019-01-14T00:00
String format = day3.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println(format);//2019-01-14T00:00:00
Another simple way,
final Calendar today = Calendar.getInstance();
today.setTime(new Date());
today.clear(Calendar.HOUR_OF_DAY);
today.clear(Calendar.HOUR);
today.clear(Calendar.MINUTE);
today.clear(Calendar.SECOND);
today.clear(Calendar.MILLISECOND);
Doing this could be easier (In Java 8)
LocalTime.ofNanoOfDay(0)
Before Java 8:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
After Java 8:
LocalDateTime.now().with(LocalTime.of(0, 0, 0))
Another way to do this would be to use a DateFormat without any seconds:
public static Date trim(Date date) {
DateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Date trimmed = null;
try {
trimmed = format.parse(format.format(date));
} catch (ParseException e) {} // will never happen
return trimmed;
}
You can either do this with the following:
Calendar cal = Calendar.getInstance();
cal.set(year, month, dayOfMonth, 0, 0, 0);
Date date = cal.getTime();
If you need format 00:00:00 in string, you should use SimpleDateFormat as below. Using "H "instead "h".
Date today = new Date();
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
//not SimpleDateFormat("dd-MM-yyyy hh:mm:ss")
Calendar calendarDM = Calendar.getInstance();
calendarDM.setTime(today);
calendarDM.set(Calendar.HOUR, 0);
calendarDM.set(Calendar.MINUTE, 0);
calendarDM.set(Calendar.SECOND, 0);
System.out.println("Current Date: " + ft.format(calendarDM.getTime()));
//Result is: Current Date: 29-10-2018 00:00:00
How do I find out the last month and its year in Java?
e.g. If today is Oct. 10 2012, the result should be Month = 9 and Year = 2012. If today is Jan. 10 2013, the result should be Month = 12 and Year = 2012.
Your solution is here but instead of addition you need to use subtraction
c.add(Calendar.MONTH, -1);
Then you can call getter on the Calendar to acquire proper fields
int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year = c.get(Calendar.YEAR);
java.time
Using java.time framework built into Java 8:
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24
earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
you can use the Calendar class to do so:
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println(format.format(cal.getTime()));
This prints : 2012.09.10 11:01 for actual date 2012.10.10 11:01
The simplest & least error prone approach is... Use Calendar's roll() method. Like this:
c.roll(Calendar.MONTH, false);
the roll method takes a boolean, which basically means roll the month up(true) or down(false)?
YearMonth class
You can use the java.time.YearMonth class, and its minusMonths method.
YearMonth lastMonth = YearMonth.now().minusMonths(1);
Calling toString gives you output in standard ISO 8601 format: yyyy-mm
You can access the parts, the year and the month. You may choose to use the Month enum object, or a mere int value 1-12 for the month.
int year = lastMonth.getYear() ;
int month = lastMonth.getMonthValue() ;
Month monthEnum = lastMonth.getMonth() ;
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
You get by using the LocalDate class.
For Example:
To get last month date:
LocalDate.now().minusMonths(1);
To get starting date of last month
LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
Similarly for Year:
To get last year date:
LocalDate.now().minusYears(1);
To get starting date of last year :
LocalDate.now().minusYears(1).with(TemporalAdjusters.lastDayOfYear());
Here's the code snippet.I think it works.
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleMonth=new SimpleDateFormat("MMMM YYYY");
cal.add(Calendar.MONTH, -1);
System.out.println(simpleMonth.format(prevcal.getTime()));
I have to use the Java Date class for this problem (it interfaces with something out of my control).
How do I get the start and end date of a year and then iterate through each date?
java.time
Using java.time library built into Java 8 and later. Specifically the LocalDate and TemporalAdjusters classes.
import java.time.LocalDate
import static java.time.temporal.TemporalAdjusters.firstDayOfYear
import static java.time.temporal.TemporalAdjusters.lastDayOfYear
LocalDate now = LocalDate.now(); // 2015-11-23
LocalDate firstDay = now.with(firstDayOfYear()); // 2015-01-01
LocalDate lastDay = now.with(lastDayOfYear()); // 2015-12-31
If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like
lastDay.atStartOfDay(); // 2015-12-31T00:00
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, 1);
Date start = cal.getTime();
//set date to last day of 2014
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 11); // 11 = december
cal.set(Calendar.DAY_OF_MONTH, 31); // new years eve
Date end = cal.getTime();
//Iterate through the two dates
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
gcal.add(Calendar.DAY_OF_YEAR, 1);
//Do Something ...
}
// suppose that I have the following variable as input
int year=2011;
Calendar calendarStart=Calendar.getInstance();
calendarStart.set(Calendar.YEAR,year);
calendarStart.set(Calendar.MONTH,0);
calendarStart.set(Calendar.DAY_OF_MONTH,1);
// returning the first date
Date startDate=calendarStart.getTime();
Calendar calendarEnd=Calendar.getInstance();
calendarEnd.set(Calendar.YEAR,year);
calendarEnd.set(Calendar.MONTH,11);
calendarEnd.set(Calendar.DAY_OF_MONTH,31);
// returning the last date
Date endDate=calendarEnd.getTime();
To iterate, you should use the calendar object and increment the day_of_month variable
Hope that it can help
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_YEAR, 1);
System.out.println(cal.getTime().toString());
cal.set(Calendar.DAY_OF_YEAR, 366); // for leap years
System.out.println(cal.getTime().toString());
An improvement over Srini's answer.
Determine the last date of the year using Calendar.getActualMaximum.
Calendar cal = Calendar.getInstance();
calDate.set(Calendar.DAY_OF_YEAR, 1);
Date yearStartDate = calDate.getTime();
calDate.set(Calendar.DAY_OF_YEAR, calDate.getActualMaximum(Calendar.DAY_OF_YEAR));
Date yearEndDate = calDate.getTime();
If you are looking for a one-line-expression, I usually use this:
new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(new java.util.Date().getYear())+"-01-01")
I assume that you have Date class instance and you need to find first date and last date of the current year in terms of Date class instance. You can use the Calendar class for this. Construct Calendar instance using provided date class instance. Set the MONTH and DAY_OF_MONTH field to 0 and 1 respectively, then use getTime() method which will return Date class instance representing first day of year. You can use same technique to find end of year.
Date date = new Date();
System.out.println("date: "+date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println("cal:"+cal.getTime());
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("cal new: "+cal.getTime());
Update: The Joda-Time library is now in maintenance mode with its team advising migration to the java.time classes. See the correct java.time Answer by Przemek.
Time Zone
The other Answers ignore the crucial issue of time zone.
Joda-Time
Avoid doing date-time work with the notoriously troublesome java.util.Date class. Instead use either Joda-Time or java.time. Convert to j.u.Date objects as needed for interoperability.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
int year = 2015 ;
DateTime firstOfYear = new DateTime( year , DateTimeConstants.JANUARY , 1 , 0 , 0 , zone ) ;
DateTime firstOfNextYear = firstOfYear.plusYears( 1 ) ;
DateTime firstMomentOfLastDayOfYear = firstOfNextYear.minusDays( 1 ) ;
Convert To java.util.Date
Convert to j.u.Date as needed.
java.util.Date d = firstOfYear.toDate() ;
You can use Jodatime as shown in this thread Java Joda Time - Implement a Date range iterator
Also, you can use gregorian calendar and move one day at a time, as shown here. I need a cycle which iterates through dates interval
PS. Piece of advice: search it first.
You can use the apache commons-lang project which has a DateUtils class.
They provide an iterator which you can give the Date object.
But I highly suggest using the Calendar class as suggested by the other answers.
First and Last day of Year
import java.util.Calendar
import java.text.SimpleDateFormat
val parsedDateInt = new SimpleDateFormat("yyyy-MM-dd")
val cal2 = Calendar.getInstance()
cal2.add(Calendar.MONTH, -(cal2.get(Calendar.MONTH)))
cal2.set(Calendar.DATE, 1)
val firstDayOfYear = parsedDateInt.format(cal2.getTime)
cal2.add(Calendar.MONTH, (11-(cal2.get(Calendar.MONTH))))
cal2.set(Calendar.DATE, cal2.getActualMaximum(Calendar.DAY_OF_MONTH))
val lastDayOfYear = parsedDateInt.format(cal2.getTime)
val instance = Calendar.getInstance()
instance.add(Calendar.YEAR,-1)
val prevYear = SimpleDateFormat("yyyy").format(DateTime(instance.timeInMillis).toDate())
val firstDayPreviousYear = DateTime(prevYear.toInt(), 1, 1, 0, 0, 0, 0)
val lastDayPreviousYear = DateTime(prevYear.toInt(), 12, 31, 0, 0, 0, 0)
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
gcal.add(Calendar.DAY_OF_YEAR, 1);
//Do Something ...
}
The GregorianCalendar creation here is pointless. In fact, going through Calendar.java source code shows that Calendar.getInstance() already gives a GregorianCalendar instance.
Regards,
Nicolas
Calendar cal = Calendar.getInstance();//getting the instance of the Calendar using the factory method
we have a get() method to get the specified field of the calendar i.e year
int year=cal.get(Calendar.YEAR);//for example we get 2013 here
cal.set(year, 0, 1); setting the date using the set method that all parameters like year ,month and day
Here we have given the month as 0 i.e Jan as the month start 0 - 11 and day as 1 as the days starts from 1 to30.
Date firstdate=cal.getTime();//here we will get the first day of the year
cal.set(year,11,31);//same way as the above we set the end date of the year
Date lastdate=cal.getTime();//here we will get the last day of the year
System.out.print("the firstdate and lastdate here\n");
java.time.YearMonth
How to Get First Date and Last Date For Specific Year and Month.
Here is code using YearMonth Class.
YearMonth is a final class in java.time package, introduced in Java 8.
public static void main(String[] args) {
int year = 2021; // you can pass any value of year Like 2020,2021...
int month = 6; // you can pass any value of month Like 1,2,3...
YearMonth yearMonth = YearMonth.of( year, month );
LocalDate firstOfMonth = yearMonth.atDay( 1 );
LocalDate lastOfMonth = yearMonth.atEndOfMonth();
System.out.println(firstOfMonth);
System.out.println(lastOfMonth);
}
See this code run live at IdeOne.com.
2021-06-01
2021-06-30