I want to select records that have a created date between the first and the last day of a given month. I calculate the month with begin and enddate the following way:
The Date "month" is just a random date inside the timeframe
Calendar cal = Calendar.getInstance();
cal.setTime(month);
int endday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int actualmonth = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
Date begin = format.parse("01." + actualmonth + "." + year);
Date end = format.parse(endday + "." + actualmonth + "." + year);
When I think about this, I'd actually have to set the daytime as well, to avoid records going missing on the last day of the month.
I feel this is kinda inelegant, anyone up for a better solution?
What I would do is create a Calendar and set the month and year to the month you want, the day to 1, hour, minute and millisecond to zero. Then take the date of that for your begin range. Then I'd add a month, and then subtract a millisecond. Take the date of that for your end range.
Calendar dateCal = Calendar.getInstance();
dateCal.set(Calendar.MONTH, month);
dateCal.set(Calendar.YEAR, year);
dateCal.set(Calendar.HOUR_OF_DAY, 0);
dateCal.set(Calendar.MINUTE, 0);
dateCal.set(Calendar.SECOND, 0);
dateCal.set(Calendar.MILLISECOND, 0);
Date startDate = dateCal.getTime();
dateCal.add(Calendar.MONTH, 1)
dateCal.add(Calendar.MILLISECOND, -1);
Date endDate = dateCal.getTime();
There are methods available in the Calendar class for getting the first and last days of the month:
getActualMaximum(Calendar.DAY_OF_MONTH)
getActualMinimum(Calendar.DAY_OF_MONTH)
okay, solved it by Paul's example:
Calendar cal = Calendar.getInstance();
cal.setTime(month);
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.getActualMinimum(Calendar.DATE), 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date begin = cal.getTime();
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.MILLISECOND, -1);
Date end = cal.getTime();
thanks everyone
Related
Given a week_of_year, how can I get the dates for the start and end of the week?
Example:
Let's say the date is Jan/1/2017.
Calendar calendar = Calendar.getInstance();
// Let's assume that we've set calendar to Jan/1/2017.
Integer week_of_year = calendar.get(Calendar.WEEK_OF_YEAR)
week_of_year would return 1. Presumably, week 1 is anything between Jan/1/2017 to Jan/7/2017.
How can I reverse lookup week_of_year=1 and get the min/max of Jan/7/2017 to Jan/6/2017? or for any other valid week_of_year value.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Start Date: " + sdf.format(cal.getTime()));
cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("End Date: " + sdf.format(cal.getTime()));
Let's say I have this code:
String day = "12";
Calendar calendar = Calendar.getInstance();
int week_of_month = calendar.get(Calendar.WEEK_OF_MONTH);
int day_of_week = calendar.get(Calendar.DAY_OF_WEEK); //For example, today is Monday
calendar.set(Calendar.HOUR_OF_DAY, 07);
calendar.set(Calendar.MINUTE, 05);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
if (day.contains("1")){ //here I set calendar day to Monday
calendar.set(Calendar.WEEK_OF_MONTH, week_of_month);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
if (day_of_week == Calendar.MONDAY) {
if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
calendar.add(Calendar.WEEK_OF_MONTH, 1);
//I add one week in case today is Monday but 07:05 was in the past
//THE PROBLEM IS CAUSED HERE..
}
}
}
if (day.contains("2")){ //here I set calendar day to Tuesday
**calendar.set(Calendar.WEEK_OF_MONTH, week_of_month); //This seems not working for some reason**
calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
if (day_of_week == Calendar.TUESDAY) {
if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
calendar.add(Calendar.WEEK_OF_MONTH, 1);
//In the example, today is Monday so this code is not running
}
}
}
The problem is that in the first if statement the calendar date is set correctly (even if System.currentTimeMillis() > calendar.getTimeInMillis()). However in the second if-statement, if I have added one week previously in the 1st-if-statement the calendar date is set for the Tuesday of the next week and not for the Tuesday of this week.
You can set the time in milliseconds to the System's current time.
calendar.setTimeInMillis(System.currentTimeMillis());
Given the assignment t = System.currentTimeMillis(), accrued at some point in the past, how do I get the millis of the same day as t in 12 pm and the day after 12 pm?
Note: this is timezone dependent. You can do as such:
import static java.util.Calendar.*;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(yourValue);
cal.set(HOUR_OF_DAY, 12);
cal.set(MINUTE, 0);
cal.set(SECOND, 0);
cal.set(MILLISECOND, 0);
// cal.getTimeInMillis() contains the wanted day at 12pm
cal.add(DAY_OF_YEAR, 1);
// cal.getTimeInMillis() now contains the wanted day plus one at 12pm
But do yourself a favour and use Joda Time, it is much easier to use in this case:
final DateTime dayAt12pm = new DateTime(yourValue).toDateMidnight()
.plusHours(12);
// dayAt12pm.getMillis() contains the wanted day at 12pm
// next day at 12pm: dayAt12pm.plusDays(1).getMillis()
//plug your "T" here.
long t = System.currentTimeMillis();
Date date = new Date(t);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar startOfDay = Calendar.getInstance();
startOfDay.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
startOfDay.set(Calendar.HOUR, 12);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.SECOND, 0);
startOfDay.set(Calendar.MILLISECOND, 0);
Date startOfDayDate = startOfDay.getTime();
System.err.println("12PM on time t is " + startOfDayDate);
startOfDay.add(Calendar.HOUR, 24);
startOfDayDate = startOfDay.getTime();
System.err.println("12PM day after t is " + startOfDayDate);
One way would be to create a Date from it and then use the Calendar class.
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 get the today's date like this:
final Calendar cal = Calendar.getInstance();
{
mYear = cal.get(Calendar.YEAR);
mMonth = cal.get(Calendar.MONTH);
mDay = cal.get(Calendar.DAY_OF_MONTH);
}
I want to calculate what was the date x days ago... anyone got something?
A better way would be to use add method instead of set:
cal.add(DAY_OF_YEAR, -2);
I.e. to be sure it works also the first day in month etc.
You can do the following :
Calendar cal=Calendar.getInstance();
int currentDay=cal.get(Calendar.DAY_OF_MONTH);
//Set the date to 2 days ago
cal.set(Calendar.DAY_OF_MONTH, currentDay-2);
then you can get the date :
cal.getTime(); //The date 2 days ago
I use the following fuction:
public static Date getStartOfDay() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
public static long getDaysAgo(Date date){
final long diff = getStartOfDay().getTime() - date.getTime();
if(diff < 0){
// if the input date millisecond > today's 12:00am millisecond it is today
// (this won't work if you input tomorrow)
return 0;
}else{
return TimeUnit.MILLISECONDS.toDays(diff)+1;
}
}
Same kind of code, but using the Joda-Time 2.3 library and Java 7.
DateTime dateTime = new DateTime( 2014, 2, 3, 7, 8, 9 );
DateTime twoDaysPrior = dateTime.minusDays( 2 );
dateTime: 2014-02-03T07:08:09.000-08:00
twoDaysPrior: 2014-02-01T07:08:09.000-08:00