I'm having trouble, finding out how to calculate or get the date from mysql (using java program) after 1 month of the initial saved date given below:
Date rDate = new Date();
java.sql.Date regDate = new java.sql.Date(rDate.getTime());
I am saving the date into a date column in mysql and I want to have another column which contains the date but one month ahead. In other words I have a registration date and I want to have an expiration date calculated automatically which allows only 1 month. Is it possible?
Grabbing the current date and set it into the Calendar format and add 1 to the month.
You can give this a try.
Date rDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(rDate);
cal.add(Calendar.MONTH, 1);
You can use Calendar class to manipulate date fields:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
Date futureDate = cal.getTime();
Related
I am having issues with the calculation of when the next Last Day of the Month is for a notification which is scheduled to be sent.
Here is my code:
RecurrenceFrequency recurrenceFrequency = notification.getRecurrenceFrequency();
Calendar nextNotifTime = Calendar.getInstance();
This is the line causing issues I believe:
nextNotifTime.add(recurrenceFrequency.getRecurrencePeriod(),
recurrenceFrequency.getRecurrenceOffset());
How can I use the Calendar to properly set the last day of the next month for the notification?
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
This returns actual maximum for current month. For example it is February of leap year now, so it returns 29 as int.
java.time.temporal.TemporalAdjusters.lastDayOfMonth()
Using the java.time library built into Java 8, you can use the TemporalAdjuster interface. We find an implementation ready for use in the TemporalAdjusters utility class: lastDayOfMonth.
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
LocalDate now = LocalDate.now(); //2015-11-23
LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth()); //2015-11-30
If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like
lastDay.atStartOfDay(); //2015-11-30T00:00
And to get last day as Date object:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
Date lastDayOfMonth = cal.getTime();
You can set the calendar to the first of next month and then subtract a day.
Calendar nextNotifTime = Calendar.getInstance();
nextNotifTime.add(Calendar.MONTH, 1);
nextNotifTime.set(Calendar.DATE, 1);
nextNotifTime.add(Calendar.DATE, -1);
After running this code nextNotifTime will be set to the last day of the current month. Keep in mind if today is the last day of the month the net effect of this code is that the Calendar object remains unchanged.
Following will always give proper results:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, ANY_MONTH);
cal.set(Calendar.YEAR, ANY_YEAR);
cal.set(Calendar.DAY_OF_MONTH, 1);// This is necessary to get proper results
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
cal.getTime();
You can also use YearMonth.
Like:
YearMonth.of(2019,7).atEndOfMonth()
YearMonth.of(2019,7).atDay(1)
See
https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#atEndOfMonth--
Using the latest java.time library here is the best solution:
LocalDate date = LocalDate.now();
LocalDate endOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
Alternatively, you can do:
LocalDate endOfMonth = date.withDayOfMonth(date.lengthOfMonth());
Look at the getActualMaximum(int field) method of the Calendar object.
If you set your Calendar object to be in the month for which you are seeking the last date, then getActualMaximum(Calendar.DAY_OF_MONTH) will give you the last day.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse("11/02/2016");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("First Day Of Month : " + calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
System.out.println("Last Day of Month : " + calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Kotlin date extension implementation using java.util.Calendar
fun Date.toEndOfMonth(): Date {
return Calendar.getInstance().apply {
time = this#toEndOfMonth
}.toEndOfMonth().time
}
fun Calendar.toEndOfMonth(): Calendar {
set(Calendar.DAY_OF_MONTH, getActualMaximum(Calendar.DAY_OF_MONTH))
return this
}
You can call toEndOfMonth function on each Date object like Date().toEndOfMonth()
hi all I am working on a form using JDateChooser I want to get the value of date inputted by the user. Is there any ways that after storing the value of date in a variable can I add 30 days from the inputted date? This is my code in passing the date to a string variable:
String dates =((JTextField)date.getDateEditor().getUiComponent()).getText();
my problem is how can I pass the date into a variable where i can be able to add an additional 30 days on it?
please help me really need this for my project .
To manipulate a String with a date value, you first need to convert to a Date using SimpleDateFormat, then you can perform manipulation using a Calendar.
SimpleDateFormat datefmt = new SimpleDateFormat("MM/dd/yyyy"); // Or format you're using
Date date = datefmt.parse(dates);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 30); // Add 30 days
Date futureDate = cal.getTime();
If you need value for insertion into a database, you will of course use PreparedStatement, so you'll need a Timestamp instead:
// From Date
Timestamp futureTimestamp = new Timestamp(futureDate.getTime());
// Directly from Calendar
Timestamp futureTimestamp = new Timestamp(cal.getTimeInMillis());
I am using postgres 9.4(Date Column) as my database and would like to know if it is possible to insert a formatted date into the database using JDBC preparedstatement in the following format (I been searching around and couldn't find anything): Aug-21-2015. This is my code
Calendar calendar = Calendar.getInstance();
java.util.Date today = calendar.getTime();
SimpleDateFormat formatter= new SimpleDateFormat("MM-dd-yyyy");
java.util.Date mydate= formatter.parse(today.toString());
preparedStatement.setDate(2,new java.sql.Date(mydate.getTime()));
needless to say that does not work and I get this error
Unparseable date: "Fri Aug 21 01:17:59 EDT 2015"
again I am trying to get this into Aug-21-2015 , I can successfully execute the code if I only insert like this
Calendar calendar = Calendar.getInstance();
java.util.Date mydate = calendar.getTime();
preparedStatement.setDate(2,new java.sql.Date(mydate.getTime()));
but it is inserted as 8-21-2015, I was thinking of maybe just saving it as 8-21-2015 format and then just parsing all of them but would prefer the 1st option.
Your date pattern is wrong: it must be:
SimpleDateFormat formatter= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
For mor information see the javadoc of SimpleDateFormat
A value in a date column itself is not formatted, it is just a date, if you want to format the date when you're reading it back out of the database, just use one of the date formatting functions.
E.g.
select to_char(your_date_column, 'MON-DD-YYYY') from yourtable
Don't know why you're converting to string and back, but today.toString() is NOT generating a text string that matches MM-dd-yyyy, so formatter.parse(today.toString()) will fail.
If the intent was to remove the time portion, in order to get "today", you can:
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.clear();
cal.set(year, month, day);
java.sql.Date today = new java.sql.Date(cal.getTimeInMillis());
Or, with Java 8:
java.sql.Date today = java.sql.Date.valueOf(LocalDate.now());
Date Format
And for your desire the insert a "formatted date", then you are confused. A date column in the database doesn't have a format, it simply stores the date value.
When you query the date column, you get the date value, which can be retrieved in Java using the ResultSet.getDate() method.
When you query the date in a tool, the tool will convert the date to a text value for display. Some tools will allow you to control the date format.
If you otherwise want to control the date format, you can convert the date to a text column in the query, using DBMS specific formatting functions.
I have a variable date1 which stores a date. I need to get the year from that. So, I want to instantiate a calendar and set its date to the one from date1. Then, I can use getYear().
How do I set the calendar
Date date1; //I set its value from database.
Calendar ca1 = Calendar.getInstance();
ca1.set(date1); // doesn't work
Is there a workaround ?
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int year= cal.get(Calendar.YEAR);// Here is your desired year
Use setTime :
Sets this Calendar's time with the given Date.
ca1.setTime(date1);
You should use:
ca1.setTime(date1);
Calendar ca1 = Calendar.getInstance();
ca1.setTime(date1);
doing only Date date1; will not work because here only reference is created
you have to do Date date1=new Date();
Suppose dbDate is the date you are getting from Database
Date date1=new Date(dbDate);
then do
Calendar ca1 = Calendar.getInstance();
ca1.setTime(date1);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get yesterday's date using Date
What is an elegant way set to a Java Date object's value to yesterday?
With JodaTime
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minus(Period.days(1));
System.out.printf("Today is : %s, Yesterday : %s", today.toString("yyyy-MM-dd"), yesterday.toString("yyyy-MM-dd"));
Do you mean to go back 24 hours in time.
Date date = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000L);
or to go back one day at the time same time (this can be 23 or 25 hours depending on daylight savings)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
These are not exactly the same due to daylight saving.
Convert the Date to a Calendar object and "roll" it back a single day. Something like this helper method take from here:
public static void addDays(Date d, int days)
{
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, days);
d.setTime(c.getTime().getTime());
}
For your specific case, just pass in days as -1 and you should be done. Just make sure you take into consideration the timezone/locale if doing extensive date specific manipulations.
you can try the follwing code:
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
As many people have already said use Calendar rather than date.
If you find you really want to use dates:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
cal.getTime();//returns a Date object
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DAY_OF_MONTH, -1);
cal1.getTime();//returns a Date object
I hope this helps.
tomred
You can try the following example to set it to previous date.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today's date is " +dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));