Java/Postgresql get next X days - java

public Date getCurrentDay() {
Calendar cal = Calendar.getInstance();
Date date = java.sql.Date.valueOf(
cal.get(cal.YEAR) + ":" +
cal.get(cal.MONTH) + ":" +
cal.get(cal.DATE) );
return date;
}
I need to make a database query where CLIENT says he wants info of next 3 days, here is my method for getting the current day, so I can get todays info, but when my client wants next 3 days, how can I make the query. How do I get the next X days?

You can call cal.add(cal.DATE, 3); to get the same time 3 days later.
You could do a method like the following:
public Date getDaysFromNow(int days) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, days);
Date date = java.sql.Date.valueOf(
cal.get(cal.YEAR) + ":" +
cal.get(cal.MONTH) + ":" +
cal.get(cal.DATE) );
return date;
}
public Date getCurrentDay() {
return getDaysFromNow(0);
}
Edit:
Note that you can also set the time to 0 and then call getTimeInMillis(), i.e.
public Date getDaysFromNow(int days, boolean endOfDay) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, endOfDay ? 23 : 0);
cal.set(Calendar.MINUTE, endOfDay ? 59 : 0);
cal.set(Calendar.SECOND, endOfDay ? 59 : 0);
cal.set(Calendar.MILLISECOND, endOfDay ? 999 : 0);
cal.add(Calendar.DATE, days);
Date date = new java.sql.Date( cal.getTimeInMillis() );
return date;
}
The endOfDay parameter is used to set the time to 23:59:59,999, thus you could get two dates for today: 2011-29-04 00:00:00,000 and 2011-29-04 23:59:59,999 with the same method.

In postgres you can use now() to get the current time. You can then use a string expression to get + 3 days.
You can play with these expressions in a postgres client.
SELECT now() + '3 days'

If your client is in Java, you can just make a helper method to get the days ahead of the current time.:
public Date getDaysAheadCurrentDate(int numberOfDaysAhead) {
if (numberOfDaysAhead <= 0) {
throw new IllegalArgumentException("The number of days ahead must be a positive integer.");
}
Calendar cal = Calendar.getInstance();
// add the number of days before creating the java.sql.Date instance.
cal.add(Calendar.DATE, numberOfDaysAhead);
Date date = java.sql.Date.valueOf(
cal.get(Calendar.YEAR) + ":" +
cal.get(Calendar.MONTH) + ":" +
cal.get(Calendar.DATE) );
return date;
}

Related

Given a calendar.week_of_year, How do I get the dates for the start and end of the week?

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

best way to calculate the first- and last-day of Week, Month and Year

He all,
I am trying to calculate the first- and last-day of Week, Month and Year.
For Month and Year it Works fine but week is wrong:
public Date[] calcDateRange(Calendar c, int day) {
Date[] dr = new Date[2];
// setMin
c.set(day, c.getActualMinimum(day));
dr[0] = c.getTime();
// setMax
c.set(day, c.getActualMaximum(day));
dr[1] = c.getTime();
return dr;
}
public void print() {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Calendar cStart = Calendar.getInstance(Locale.GERMANY);
cStart.setFirstDayOfWeek(Calendar.MONDAY);
System.out.println("startdate: " + sdf.format(cStart.getTime()));
Date[] minMaxD = calcDateRange(cStart, Calendar.DAY_OF_WEEK);
System.out.println("start_of_week:\t" + sdf.format(minMaxD[0]) + "\nend_of_week:\t" + sdf.format(minMaxD[1]));
minMaxD = calcDateRange(cStart, Calendar.DAY_OF_MONTH);
System.out.println("start_of_month:\t" + sdf.format(minMaxD[0]) + "\nend_of_month:\t" + sdf.format(minMaxD[1]));
minMaxD = calcDateRange(cStart, Calendar.DAY_OF_YEAR);
System.out.println("start_of_year:\t" + sdf.format(minMaxD[0]) + "\nend_of_year:\t" + sdf.format(minMaxD[1]));
}
Can someone help me to find my mistakes?
What is the best way to calculate the dates?
Output:
startdate: 20.03.2014
start_of_week: 23.03.2014 <--- wrong, should be '17.03.2014'
end_of_week: 22.03.2014 <--- wrong, should be '23.03.2014'
start_of_month: 01.03.2014
end_of_month: 31.03.2014
start_of_year: 01.01.2014
end_of_year: 31.12.2014
Thank you in advance.
//edit
Currently I use the following methode, but im not realy happy with it:
public Date[] calcDateRange(Calendar c, int day) {
int fdow = c.getFirstDayOfWeek();
c.setFirstDayOfWeek(Calendar.SUNDAY);
Date[] dr = new Date[2];
// setMin
c.set(day, c.getActualMinimum(day));
//..setSecondsMinutes
if (day == Calendar.DAY_OF_WEEK)
c.add(day, 1); // German Week correction
dr[0] = c.getTime();
// setMax
c.set(day, c.getActualMaximum(day));
//..setSecondsMinutes
if (day == Calendar.DAY_OF_WEEK)
c.add(day, 1); // German Week correction
dr[1] = c.getTime();
c.setFirstDayOfWeek(fdow);
return dr;
}
Joda Time library is useful for things around dates and times. As I cant comment yet I am posting it as an answer. I suggest you to look into it.
http://www.joda.org/joda-time/
//EDIT:
I think that I have found where is the mistake.
The start of the week is incorrect because:
You call
Date[] minMaxD = calcDateRange(cStart, Calendar.DAY_OF_WEEK);
and then on the line in calcDateRange function
c.set(day, c.getActualMinimum(day));
the following will happen:
the day variable is an int with value 7
c.getActualMinimum(day) will return 1 because of the fact that getActualMinimum(7) method returns the minimum for field 7 which is "DAY_OF_WEEK" and the minimum for this field equals "SUNDAY" which is int with value 1
the you c.set(7,1) which will set the "DAY_OF_WEEK" as 1 ("SUNDAY")
On the
dr[0] = c.getTime();
line you will get time for SUNDAY because you set it and the date then returns 23.3.
Principal is the same for the end of week:
On the line
c.set(day, c.getActualMaximum(day));
you set "DAY_OF_WEEK" to SATURDAY and then it will return you date 22.3.
//EDIT2:
method for calculating start and end of week
public Date[] calcDateRangeWeek(Calendar c, int day) {
Date[] dr = new Date[2];
// setMin
c.set(day, Calendar.MONDAY);
dr[0] = c.getTime();
// setMax
c.set(day, Calendar.SUNDAY);
dr[1] = c.getTime();
return dr;
}
If you can use Java 8, I would use the TemporalAdjusters from java.time:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import static java.time.DayOfWeek.*;
import static java.time.temporal.TemporalAdjusters.*;
public void print() {
DateTimeFormatter german = DateTimeFormatter.ofPattern("dd.MM.yyyy");
LocalDate start = LocalDate.now();
System.out.printf("startdate: %s%n", start.format(german));
System.out.printf("start_of_week:\t%s%nend_of_week:\t%s%n",
start.with(previousOrSame(MONDAY)).format(german),
start.with(nextOrSame(SUNDAY)).format(german));
System.out.printf("start_of_month:\t%s%nend_of_month:\t%s%n",
start.with(firstDayOfMonth()).format(german),
start.with(lastDayOfMonth()).format(german));
System.out.printf("start_of_year:\t%s%nend_of_year:\t%s%n",
start.with(firstDayOfYear()).format(german),
start.with(lastDayOfYear()).format(german));
}
If you can't use Java 8, these features all come from the Joda Time library.
You can use Java Calendar like this
Calendar cal = Calendar.getInstance();
Date now = cal.getTime();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date mondayOfTheWeek = cal.getTime();
....
The calendar recalculate the associated Date automatically
EDIT: for the last day of the month
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
And you can do the same with Calendar.YEAR and Calendar.DAY_OF_YEAR

How to compare item of set collection to current Date?

I have the following set and need to compare its date instance with the current date. Although both dates are the same but the comparison returns false !!
MyClass.java
import java.util.Date;
public class MyClass {
private Date date;
...
}
My Code
....
Set <MyClass> myclass = new HashSet();
I populate it with some data here...
for(MyClass m : myclass)
{
System.err.println("date>>:" + trim(m.getDate())); //returns 2013-08-08
System.err.println("date>>:" + trim(getCurrentDate())); //returns 2013-08-08
System.err.println("boolean:" +
trim(m.getDate()).equals(trim(getCurrentDate()))); //returns false
}
}
public Date getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
dateFormat.format(date));
return date;
}
public 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();
}
Dates are not same, they may differ by millis/sec. Date equals doesn't depend upon format of date but compares value. Below code would return false as well:
Date d1 = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
Date d2 = new Date();
f.format(d2);
System.out.println(d1);//e.g. Thu Aug 08 12:09:24 IST 2013
System.out.println(d2);//e.g. Thu Aug 08 12:09:26 IST 2013
System.out.println(d1.equals(d2));//false
Date.equals compares time (Date.getTime()), equals will return true only if they matches:
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}
Per javadoc:
The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object.
Thus, two Date objects are equal if and only if the getTime method returns the same long value for both.
Date.getTime return the number of milliseconds since January 1, 1970, 00:00:00 GMT
So in you updated question with trim, consider you are comparing two long values of time in millis.
If you require to compare yyyy-MM-dd values of two different date instances, consider using String.equals instead (hack way):
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
String date1 = f.format(new Date());//2013-08-08
String date2 = f.format(new Date());//2013-08-08
System.out.println(date1.equals(date2));
Each time you call getCurrentDate, you might receive a new date. Formatting it the way you do is essentially a no-op and the date still carries its hours, minutes, seconds and milliseconds.
So they are actually proably different for real.
You could remove this extra information to get the desired behaviour.
The Date class includes the time of the day to millisecond precision, and the time counts when comparing for equality.
To compare only the "date" part you can do one of several things, for example format the dates as year-month-day and compare the resulting strings, or create Calendar objects from the dates and compare the year, month and day individually. Another option is to make sure the Dates you compare have the same hour of the day, for example 12:00, that way you can use the equals method.
You can use GregorianCalendar and Calendar#get(..) to only compare year, month, and day.
There is a perfect sample from the javadoc :
// get the supported ids for GMT-08:00 (Pacific Standard Time)
String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
// if no ids were returned, something is wrong. get out.
if (ids.length == 0)
System.exit(0);
// begin output
System.out.println("Current Time");
// create a Pacific Standard Time time zone
SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
// set up rules for Daylight Saving Time
pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
// create a GregorianCalendar with the Pacific Daylight time zone
// and the current date and time
Calendar calendar = new GregorianCalendar(pdt);
Date trialTime = new Date();
calendar.setTime(trialTime);
// print out a bunch of interesting things
System.out.println("ERA: " + calendar.get(Calendar.ERA));
System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
System.out.println("DATE: " + calendar.get(Calendar.DATE));
System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
System.out.println("DAY_OF_WEEK_IN_MONTH: "
+ calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
System.out.println("ZONE_OFFSET: "
+ (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
System.out.println("DST_OFFSET: "
+ (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));
Actually there is a problem in your method..
public Date getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
dateFormat.format(date);
return date;
}
dateFormat.format(date) will return a String date in yyyy-MM-dd format but you are returning date from this method which will return the Date in 'Thu Aug 08 12:21:34 IST 2013' this format not in '2013-08-08' this. So you should take the String as return from this method and then compare it by equals.
Try this, I think this should help you.

How to ignore time while checking date using before(Date d)

I know alternate methods to check next date but I would like to know is there any possibility of ignoring checking time when using before.
I have the following code
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
try {
if (fired == true) {
return;
} else {
// first time fired
fired = true;
}
String date = checkDigit(monthOfYear + 1) + "/"
+ checkDigit(dayOfMonth) + "/" + year;
strDate = date;
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date d=df.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
if(d.before(cal.getTime()))
{
etDOB.setText(strDate);
}
else
{
Toast.makeText(context, "Enter Valid Date Of Birth", Toast.LENGTH_SHORT).show();
etDOB.setText(" ");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
d.before(cal.getTime()) checking date but if the selected Date is next Date than it also checking time
Example :
Date value selected is feb 24 2013 so d contains the same
cal.getTime() also contains feb 24 2013
but the first date having the time 00:00:00 GMT+5:30 and second has the time 1:00:00 GMT+5:30 this cause the condition to fail. So my question is how do Ignore before to check time.
You can format and parse the date from cal.getTime() using df (SimpleDateFormat("MM/dd/yyyy")) which will get rid of time and then compare the result with d.
While createing the Calendar Object
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
cal.set(Calendar.Minute, 0);
cal.set(Calendar.Second, 0);
now your condition will not fail

Calculating a month as a "between" period in java

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

Categories

Resources