This question already has answers here:
Adding days to a date in Java [duplicate]
(6 answers)
Closed 3 years ago.
I need to set up a program that compares the date of creation of a date object(say date object 1), with another a future date or date object(say date object 2) that represents the deadline. For example, if i create an initial datetime object, I want to be able to compare the current date of creation with lets say, a date 18 days after said date(deadline).I don't want to hardcode the actual dates and deadlines. It should return a bool( true when current date is equal or later than the deadline date, false otherwise). Eventually, I'll want to store the date of the deadline in an external database, then when appropriate compare said deadline date with the current date.
I can get the current date with the code below but unsure how to obtain a deadline day by specifyinging "x" days from the current date instead of hardcoding the date values.
I know how to create a date object(as show below) but i want to be able to create a deadline date object in correspondence to the current date of creation, store the deadline date in a database, while continually comparing the current date with the deadline date.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16
To create a "non-hardcoded deadline" as you put it;
LocalDate currentDate = LocalDate.now();
LocalDate deadline = LocalDate.now().plusDays(10); // x = 10
storeDb(deadline);
Then later for deadline check;
LocalDate deadline = getDeadlineFromDb();
LocalDate currentDate = LocalDate.now();
if (currentDate.isAfter(deadline)) {
// deadline has passed
}
For more details check; Introduction to the Java 8 Date/Time API
Related
This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Why Java Calendar set(int year, int month, int date) not returning correct date? [duplicate]
(3 answers)
Closed 3 years ago.
Im using File.getlastmodified() to get last modifies of files but for some reason (probably UIT) its printing wrong date and month (year is fine)
Im getting last modifed with the above method and saving it to Long
//This should ideally conver the last modified to human radable format
but its returning wrong month adn date
like----> 27/11/2018
shows as---> 28/10/2018
c = Calendar.getInstance();
Long epoch = files[i].lastModified();
epoch+=32400L;
c.setTimeInMillis(epoch); //im converting the milliseconds to human readable formate
int year=c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);
int day=c.get(Calendar.DATE);
The value is not incorrect.
You are using the Calendar incorrectly. Checking the documentation you can see the value returned for Month.
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Source
Now, for the day, I would suspect the addition of 32 seconds could be the problem. But most probably the timezone. Indeed, the method return a value on GMT.
Note that I have check with a file modified the "2019-04-17 14:52:13" and get the correct result. Also, you can format the Calendar using a SimpleDateFormat instance instead of extracting the value like this.
private static String formatEpoch(long epoch) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(epoch));
}
Or, we can never mention this enough, using a more recent API for date with Instant.
private static String formatEpoch(long epoch) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
return formatter.format(Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()));
}
An instant is a date-time at GMT, so we add the locale timezone before formatting it with a DateTimeFormatter to provide a value like :
2019-04-17T14:52:13.118
I have a mySQL table of users containing the users' birthdays.
i have stored the date from sql as the variable DateOfBirth.
Now, I want to set the minimum selectable date of a jDateChooser named GameDateChooser as 15 years past the birthday
and the maximum selectable date to the current date.
i tried searching for other articles but they didnt answer my question
From java doc there are setSelectableDateRange, which can accept two dates, min and max :
public void setSelectableDateRange(java.util.Date min, java.util.Date max)
In your case you need something like this :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -15);//15 year before
Date min = cal.getTime();
Date max = new Date();//actual date
JDateChooser jDateChooser = new JDateChooser();
//set your dates in your JDateChooser
jDateChooser.setSelectableDateRange(min, max);
Even when setSelectableDateRange() requires two oldfashioned Date objects, I would still prefer to use the modern classes for the age calculation, not the outdated Calendar:
LocalDate dateOfBirth = LocalDate.of(1959, Month.FEBRUARY, 15);
Instant min = dateOfBirth.plusYears(15)
.atStartOfDay(ZoneId.systemDefault())
.toInstant();
jDateChooser.setSelectableDateRange(Date.from(min), new Date());
LocalDate and Instant come built-in with Java 8 and later and are also available for Java 6 and 7. Date.from(Instant) is Java 8 and later only, for Java 6 and 7 there are other conversion options. A sufficiently new MySQL JDBC driver should be able to retrieve a LocalDate from the database.
This question already has answers here:
String -> java.util.Date -> java.sql.Date (with time stamp)
(3 answers)
Closed 6 years ago.
Hello i'm defining a variable in which i want to stock date-time input.
I gave this variable a format which is yyyy-mm-dd hh:MM.
But in the database it keeps showing me only this format yyyy-mm-dd without hh:MM
The code
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd hh:MM");
java.util.Date date = sdf1.parse(rs.getString("dateMaint"));
java.sql.Date sqlStartDate = new Date(date.getTime());
mc.setDateMaint(sqlStartDate );
Also check if the database data type for your data is correct. This is dabase vendor dependant, for example an Oracle date type contains both time and date, but MS SQL server date means only date part: https://msdn.microsoft.com/en-us/library/bb630352.aspx
public static java.sql.Timestamp convertToSqlDateTime(Date utilDate){
return new java.sql.Timestamp(utilDate.getTime());
}
Normally, java.sql.Date only returns a date-only value and time will be discarded. So, in order to get time also, java.sql.TimeStamp must be used.
TimeStamp constructs a Timestamp object using a milliseconds time value. The integral seconds are stored in the underlying date value; the fractional seconds are stored in the nanos field of the Timestamp object.
For this purpose, utilDate.getTime() is used to return the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date Object.
For more information link: Source
I want to get today's day and a date which is one year after today. For example, if today is 2015-9-18, next year is 2016-9-18.
I would like to use Java LocalDate.
The current date is simply retrieved with:
LocalDate now = LocalDate.now();
Then, you can add one year to this date, using the method plusYears(years):
LocalDate oneYearAfter = now.plusYears(1);
LocalDate contains various methods to ease the task of adding or subtracting a temporal amount (like plusDays, plusMonths; the most general being plus(amount, unit) adding the amount given for the specified unit of time).
This question already has answers here:
How to check if a date Object equals yesterday?
(9 answers)
Closed 8 years ago.
I have these codes to get the date today in my server
DefaultTableModel dnow = MyDB.DataTable("SELECT date_format(now(),'%m-%d-%Y')");
and these code for the formatting for the date.
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
now how can I get the date of yesterday?
should I just minus it with one?
An alternative approach is to do the math in SQL. The statement may vary depending on what database platform you're using.
DefaultTableModel dnow =
MyDB.DataTable("SELECT date_format(now() - INTERVAL 1 DAY,'%m-%d-%Y')");
No, build a Date (or better yet use joda's DateTime object) and then do your arithmetic. I will give you two solutions, one with Joda and the other without, starting with without:
Date d = format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()));
d.add(Calendar.DATE, -1);
Now, using joda:
DateTime d = new DateTime(format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()))).minusDays(1);
This should work perfect for you,
Calendar cal = Calendar.getInstance()
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date = "+ cal.getTime());
This will simply subtract 1 day from the current calendar date, providing you yesterdays date
If you store your timestamps internally as POSIX times (milliseconds since MN Jan 1, 1970) then you can add or subtract a day to any time stamp as easily as:
Date today = new Date(); // today
Date tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000)); // tomorrow
The huge bonus to POSIX time is that it is always in UTC. UTC is a global, "fixed" point of reference. Then if you need to need to have this date displayed for the user in any time zone, in any daylight savings zone, for any place that is accounted for in the Olson Time Zone database, you can simply create a Calendar:
GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setCalendar(gc);
sdf.applyPattern("MM-dd-yyyy");
// Now your formatter is set with the pattern and a time zone-aware Calendar.
// The world is at your command
String myOutput = sdf.format(tomorrow);
I highly recommend dealing with timestamps internally in your data model in some form of UTC representation. Doing date arithmetic with POSIX time (or Julian Day Numbers, or Modified Julian Day Numbers) is easy peasy, and the Java date/time API has enough capability to deal with most local time conversions without much fuss from you.