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 actually have found the last three dates and what I want to do is subtract 5 hours and 45 minutes from each date. How can implement it?
The code I have done so far is:
public static List<Date> getPastThreeDays() {
List<Date> pDates = new ArrayList<Date>();
for (int i = 1; i <= 3; i++) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -i);
Date date = cal.getTime();
String pastDate = sdf.format(date);
Date pstThreesDates;
try {
pstThreesDates = sdf.parse(pastDate);
pDates.add(pstThreesDates);
} catch (ParseException e) {
e.printStackTrace();
}
}
return pDates;
}
public static void main(String[] args) throws ParseException {
// for getting past three dates
System.out.println("-----Formatted Past Three Days-----");
List<Date> pastThreeDatesList = getPastThreeDays();
for (Date date : pastThreeDatesList) {
System.out.println("Orignal:" + date);
}
You can use the API DateTime from JodaTime and make something like this:
Date date = new Date();
DateTime dateTime = new DateTime(date);
DateTime newDateTime = dateTime.minusHours(5).minusMinutes(45);
How about stay out of dependencies?
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -i);
Calendar calLess5_45 = Calendar.getInstance();
calLess5_45.setTimeInMillis(cal.getTimeInMillis() - (1000*60*45) - (1000*60*60*5));
or with Date:
Date initialDate = cal.getTime();
Date dateLess5_45 = new Date(initialDate.getTime() - (1000*60*45) - (1000*60*60*5));
convert the date into milliseconds then substract the 5hr 45min from it as follows:
public static void main(String[] args) {
System.out.println("-----Formatted Past Three Days-----");
List<Date> pastThreeDatesList = getPastThreeDays();
for (Date date : pastThreeDatesList) {
System.out.println("Orignal:"+date);
long mDateMills= date.getTime() - ((5*3600 *1000)+ 45*60*1000); //you convert your date to millisecond then subtract 5h45min( in milliseconds from it)
String mNewDate= millsToDateFormat(mDateMills);
System.out.println("new Date:"+mNewDate);
}
}
public static String millsToDateFormat(long mills) {
Date date = new Date(mills);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String dateFormatted = formatter.format(date);
return dateFormatted;
}
java.time
The troublesome old date-time classes are now legacy, supplanted by the java.time classes.
A time zone is crucial in determining a date and in adding subtracting days. The date, and length of day, varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtNow = ZonedDateTime.now( z );
Subtract a day. Accounts for anomalies such as Daylight Saving Time.
ZonedDateTime zdtYesterday = zdtNow.minusDays( 1 );
Subtract a duration of five hours and forty-five minutes.
Duration d = Duration.ofHours( 5 ).plusMinutes( 45 ); // or Duration.parse( "PT5H45M" ) in standard ISO 8601 string format.
ZonedDateTime zdtEarlier = zdtYesterday.minus( d ) ;
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
I have the date of several events expressed in milliseconds[1], and I want to know which events are inside the current week and the current month, but I can't figure out how to obtain the first day (day/month/year) of the running week and convert it to milliseconds, the same for the first day of the month.
[1]Since January 1, 1970, 00:00:00 GMT
This week in milliseconds:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println("Start of this week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// start of the next week
cal.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("Start of the next week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
This month in milliseconds:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of the month
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Start of the month: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// get start of the next month
cal.add(Calendar.MONTH, 1);
System.out.println("Start of the next month: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
The first day of week can be determined with help of java.util.Calendar as follows:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
long firstDayOfWeekTimestamp = calendar.getTimeInMillis();
The first day of month can be determined as follows:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DATE) > 1) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of month.
}
long firstDayOfMonthTimestamp = calendar.getTimeInMillis();
Pretty verbose, yes.
Java 7 will come with a much improved Date and Time API (JSR-310). If you can't switch yet, then you can as far use JodaTime which makes it all less complicated:
DateTime dateTime = new DateTime(timestamp);
long firstDayOfWeekTimestamp = dateTime.withDayOfWeek(1).getMillis();
and
DateTime dateTime = new DateTime(timestamp);
long firstDayOfMonthTimestamp = dateTime.withDayOfMonth(1).getMillis();
java.time
The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.
The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.
Instant
The Instant class represents a moment on the timeline in UTC.
The java.time framework has a resolution of nanoseconds, or 9 digits of a fractional second. Milliseconds is only 3 digits of a fractional second. Because millisecond resolution is common, java.time includes a handy factory method.
long millisecondsSinceEpoch = 1446959825213L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );
millisecondsSinceEpoch: 1446959825213 is instant: 2015-11-08T05:17:05.213Z
ZonedDateTime
To consider current week and current month, we need to apply a particular time zone.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
In zoneId: America/Montreal that is: 2015-11-08T00:17:05.213-05:00[America/Montreal]
Half-Open
In date-time work, we commonly use the Half-Open approach to defining a span of time. The beginning is inclusive while the ending in exclusive. Rather than try to determine the last split-second of the end of the week (or month), we get the first moment of the following week (or month). So a week runs from the first moment of Monday and goes up to but not including the first moment of the following Monday.
Let's the first day of the week, and last. The java.time framework includes a tool for that, the with method and the ChronoField enum.
By default, java.time uses the ISO 8601 standard. So Monday is the first day of the week (1) and Sunday is last (7).
ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );
That week runs from: 2015-11-02T00:17:05.213-05:00[America/Montreal] to 2015-11-09T00:17:05.213-05:00[America/Montreal]
Oops! Look at the time-of-day on those values. We want the first moment of the day. The first moment of the day is not always 00:00:00.000 because of Daylight Saving Time (DST) or other anomalies. So we should let java.time make the adjustment on our behalf. To do that, we must go through the LocalDate class.
ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
firstOfWeek = firstOfWeek.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );
That week runs from: 2015-11-02T00:00-05:00[America/Montreal] to 2015-11-09T00:00-05:00[America/Montreal]
And same for the month.
ZonedDateTime firstOfMonth = zdt.with ( ChronoField.DAY_OF_MONTH , 1 );
firstOfMonth = firstOfMonth.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextMonth = firstOfMonth.plusMonths ( 1 );
That month runs from: 2015-11-01T00:00-04:00[America/Montreal] to 2015-12-01T00:00-05:00[America/Montreal]
YearMonth
Another way to see if a pair of moments are in the same month is to check for the same YearMonth value.
For example, assuming thisZdt and thatZdt are both ZonedDateTime objects:
boolean inSameMonth = YearMonth.from( thisZdt ).equals( YearMonth.from( thatZdt ) ) ;
Milliseconds
I strongly recommend against doing your date-time work in milliseconds-from-epoch. That is indeed the way date-time classes tend to work internally, but we have the classes for a reason. Handling a count-from-epoch is clumsy as the values are not intelligible by humans so debugging and logging is difficult and error-prone. And, as we've already seen, different resolutions may be in play; old Java classes and Joda-Time library use milliseconds, while databases like Postgres use microseconds, and now java.time uses nanoseconds.
Would you handle text as bits, or do you let classes such as String, StringBuffer, and StringBuilder handle such details?
But if you insist, from a ZonedDateTime get an Instant, and from that get a milliseconds-count-from-epoch. But keep in mind this call can mean loss of data. Any microseconds or nanoseconds that you might have in your ZonedDateTime/Instant will be truncated (lost).
long millis = firstOfWeek.toInstant().toEpochMilli(); // Possible data loss.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Attention!
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
is good idea, but there is some issue:
For example, i'm from Ukraine and calendar.getFirstDayOfWeek() in my country is 2 (Monday).
And today is 1 (Sunday). In this case calendar.add not called.
So, correct way is change ">" to "!=":
while (calendar.get(Calendar.DAY_OF_WEEK) != calendar.getFirstDayOfWeek()) {...
You can use the java.time package (since Java8 and late) to get start/end of day/week/month.
The util class example below:
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
public class DateUtil {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public static LocalDateTime startOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
}
public static LocalDateTime endOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
}
public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
}
//note that week starts with Monday
public static LocalDateTime startOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
}
//note that week ends with Sunday
public static LocalDateTime endOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
}
public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
}
public static LocalDateTime startOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDateTime endOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.lastDayOfMonth());
}
public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
}
public static long toMills(final LocalDateTime localDateTime) {
return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
}
public static Date toDate(final LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
}
public static String toString(final LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
}
#Test
public void test() {
//day
final LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
System.out.println("Start of day: " + toString(startOfDay()));
System.out.println("End of day: " + toString(endOfDay()));
System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
final LocalDateTime yesterday = now.minusDays(1);
System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
final LocalDateTime tomorrow = now.plusDays(1);
System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
//week
System.out.println("Start of week: " + toString(startOfWeek()));
System.out.println("End of week: " + toString(endOfWeek()));
System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
final LocalDateTime previousWeek = now.minusWeeks(1);
System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
final LocalDateTime nextWeek = now.plusWeeks(1);
System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
//month
System.out.println("Start of month: " + toString(startOfMonth()));
System.out.println("End of month: " + toString(endOfMonth()));
System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
final LocalDateTime previousMonth = now.minusMonths(1);
System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
final LocalDateTime nextMonth = now.plusMonths(1);
System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
}
}
Test output:
Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false
I have created some methods for this:
public static String catchLastDayOfCurrentWeek(String pattern) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
return calendarToString(cal, pattern);
}
public static String catchLastDayOfCurrentWeek(String pattern) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.add(Calendar.MILLISECOND, -1);
return calendarToString(cal, pattern);
}
public static String catchTheFirstDayOfThemonth(Integer month, pattern padrao) {
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
return calendarToString(cal, pattern);
}
public static String catchTheLastDayOfThemonth(Integer month, String pattern) {
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.set(cal.get(Calendar.YEAR), month, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendarToString(cal, pattern);
}
public static String calendarToString(Calendar calendar, String pattern) {
if (calendar == null) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
return format.format(calendar.getTime());
}
You can see more here.
To get the first day of the month, simply get a Date and set the current day to day 1 of the month. Clear hour, minute, second and milliseconds if you need it.
private static Date firstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, 1);
return calendar.getTime();
}
First day of the week is the same thing, but using Calendar.DAY_OF_WEEK instead
private static Date firstDayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 1);
return calendar.getTime();
}
In this case:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY); <---- is the current hour not 0 hour
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
So the Calendar.HOUR_OF_DAY returns 8, 9, 12, 15, 18 as the current running hour.
I think will be better change such line by:
c.set(Calendar.HOUR_OF_DAY,0);
this way the day always begin at 0 hour
Get First date of next month:-
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
String selectedDate="MM-dd-yyyy like 07-02-2018";
Date dt = df.parse(selectedDate);`enter code here`
calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + 1);
String firstDate = df.format(calendar.getTime());
System.out.println("firstDateof next month ==>" + firstDate);
A one-line solution using Java 8 features
In Java
LocalDateTime firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay(); // 2020-06-08 00:00 MONDAY
LocalDateTime firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay(); // 2020-06-01 00:00
// Convert to milliseconds:
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
In Kotlin
val firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay() // 2020-06-08 00:00 MONDAY
val firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay() // 2020-06-01 00:00
// Convert to milliseconds:
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
You should be able to convert your number to a Java Calendar, e.g.:
Calendar.getInstance().setTimeInMillis(myDate);
From there, the comparison shouldn't be too hard.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
/**
This Program will display day for, 1st and last days in a given month and year
#author Manoj Kumar Dunna
Mail Id : manojdunna#gmail.com
*/
public class DayOfWeek {
public static void main(String[] args) {
String strDate = null;
int year = 0, month = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter YYYY/MM: ");
strDate = sc.next();
Calendar cal = new GregorianCalendar();
String [] date = strDate.split("/");
year = Integer.parseInt(date[0]);
month = Integer.parseInt(date[1]);
cal.set(year, month-1, 1);
System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DAY_OF_YEAR, -1);
System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
}
}
Simple Solution:
package com.util.calendarutil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class CalUtil {
public static void main(String args[]){
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Date dt = null;
try {
dt = df.parse("23/01/2016");
} catch (ParseException e) {
System.out.println("Error");
}
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
Date startDate = cal.getTime();
cal.add(Calendar.DATE, 6);
Date endDate = cal.getTime();
System.out.println("Start Date:"+startDate+"End Date:"+endDate);
}
}
i use this trick to get the first day of the current month
note the order is
1 for Sunday
2 for Monday
3 for Tuesday
.... and so on
Calendar cal = new GregorianCalendar();
int startDay = cal.get(Calendar.DAY_OF_YEAR) % 7 + 1;
System.out.println(startDay);
public static void main(String[] args) {
System.out.println(getMonthlyEpochList(1498867199L,12,"Monthly"));
}
public static Map<String,String> getMonthlyEpochList(Long currentEpoch, int noOfTerms, String timeMode) {
Map<String,String> map = new LinkedHashMap<String,String>();
int month = 0;
while(noOfTerms != 0) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, month);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date monthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date monthLastDay = calendar.getTime();
map.put(getMMYY(monthFirstDay.getTime()), monthFirstDay + ":" +monthLastDay);
month--;
noOfTerms--;
}
return map;
}