Finding difference between two dates using Joda in Java - java

I'm using Joda-Time and trying to find the difference between dates.
Is there something wrong with my code?
Here's my code :
LocalDate startDate = new LocalDate (19990-7-18);
LocalDate endDate = new LocalDate (2013-07-18);
Years Age = Years.yearsBetween(startDate, endDate);
int Age1 = Age.getYears();
String Age2 = new Integer(Age1).toString();
I'm using JOptionPane to view the result, and its telling I got 0 on (age1).

You need to add quotation marks " to your LocalDate definitions to use the constructor that takes a String parameter:
LocalDate startDate = new LocalDate("1999-07-18");
LocalDate endDate = new LocalDate("2013-07-18");
What you have written evaluates to longs, and the two dates constructed will in fact be 0 years apart.

Related

Difference between two dateFields in Vaadin

I'm having some problem with calculate days between two dateFields. I already tried
`
DateField dateStart = new DateField();
DateField dateEnd = new DateField();
DateTime start = new DateTime(dateStart);
DateTime end = new DateTime(dateEnd);
int days = Days.daysBetween(new DateTime(start), new DateTime(end)).getDays();
`
Here is the error that I get after run this code
java.lang.IllegalArgumentException: No instant converter found for type: com.vaadin.ui.DateField
I also already tried using ChronoUnit
LocalDate startDate = LocalDate.now().minusDays(1);
LocalDate endDate = LocalDate.now();
long days = Period.between(startDate, endDate).getDays();
assertEquals(1, days);
long days2 = ChronoUnit.DAYS.between(startDate, endDate);
assertEquals(1, days2);
and also JudoTime
DateTime startDate = new DateTime().minusDays(1);
DateTime endDate = new DateTime();
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Both code I get NullPointerException error. Is there any way that I can get number of days.
The other answers show how to calculate the difference between two dates in days using Java 8. But your actual problem is how to get the dates from Vaadin DateField (as p.streef and Ramachandran G A pointed out in the comments). Use dateStart.getValue() for that which will return a java.util.Date and can be passed to new DateTime().
This is simplest way to find the intermediate date values using java 8.
LocalDate startDate = LocalDate.now().minusDays(1);
LocalDate endDate = LocalDate.now();
long days = Period.between(startDate, endDate).getDays();
System.out.println(days);
The following snippet works. One of the reason for no instant converter error that you see is what time of the day do you want the day to be at. I mentioned start of day here. Interesting read here (How to convert Joda Localdate to Joda DateTime?) .
LocalDateTime startDateTime = LocalDate.now().atStartOfDay().minusDays(1);
LocalDateTime endDateTime = LocalDate.now().atStartOfDay();
long days = Period.between(startDateTime.toLocalDate(), endDateTime.toLocalDate()).getDays();
System.out.println("The difference in dates is " + days);
At the output : The difference in dates is 1

get day month year from java.sql.date

My question is simple my SQL query from java returns a date and assign it to a java.sql.Date variable.
however i want to get each of the day, month and year as int. It seems that the methods getDay(),getMonth() are deprecated.
Are there any other way to achieve this?
what i tried for testing is:
String date = "2015-04-12";
java.sql.Date dat = java.sql.Date.valueOf(date);
now i want year, month and day in an int variable each.
You can do the following:
String date = "2015-04-12";
java.sql.Date dat = java.sql.Date.valueOf(date);
//create calander instance and get required params
Calendar cal = Calendar.getInstance();
cal.setTime(dat);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
Since java.sql.Date extends java.util.Date you could use its inherited toLocalDate() method to get instance of LocalDate (available since Java 8) which supports many get...() methods like
String date = "2015-04-12";
java.sql.Date dat = java.sql.Date.valueOf(date);
LocalDate localDate = dat.toLocalDate();
System.out.println(localDate.getDayOfMonth());
System.out.println(localDate.getMonthValue());
System.out.println(localDate.getYear());
Output:
12
4
2015

format days for joda.time.Days

I'm using Joda's daysBetween() method to compare two dates. When I use this method, it returns a value that has P and D concatenated to the ends of the day value. For example,
DateTime todaysDate = DateTime.now();
DateTime notificationDate = new DateTime(qaCase.getFollowUpNotificationDate());
return Days.daysBetween(todaysDate, notificationDate);
This is what the method is returning (see image)
I would like it to display just the number. Thanks
You can use the method getDays() of the returned Days object.
For example,
DateTime todaysDate = DateTime.now();
DateTime notificationDate = new DateTime(todaysDate).plusDays(5);
Days daysBetween = Days.daysBetween(todaysDate, notificationDate);
System.out.println("Days between = " + daysBetween.getDays());
gives the output:
Days between = 5
See getDays for more information.

convert java.sql.Timestamp to java.sql.Date

I have a Timestamp and Date variables and i want to compare it for equality (only date part of course). It was surprise for me that contructor Date(long) saves time part, so this code does not work correct:
date = resultSet.getDate(1);
timestamp = resultSet.getTimestamp(2);
//...
if (date.equals(new Date (timestamp.getTime())) ...
I solve this with code like:
DateFormat dateFormat = new SimpleDateFormat ("yyyyMMdd");
if (date.equals(dateFormat.parse(dateFormat.format(timestamp)))) ...
Or i can convert timestamp to date in sql query, but i need a timestamp representation too. Is there a better way to cut a time part from Timestamp.
Java 8 approach of conversion:
Date date = Date.valueOf(timestamp.toLocalDateTime().toLocalDate());
And vice versa:
Timestamp timestamp = Timestamp.valueOf(date.toLocalDate().atStartOfDay());
Using the method from this answer we get:
date = resultSet.getDate(1);
timestamp = resultSet.getTimestamp(2);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date);
cal2.setTimeInMillis(timestamp.getTime());
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
It's worth reading the linked answer as it talks about the shortcomings of this method with respects to timezones and so on (and some of the other answers to that question give alternate approaches which you may prefer).
You have three options with this one.
First is to use Yoda time and class DateTimeComparator.getDateOnlyInstance()
Second is to use commons from apache and DateUtils.isSameDay()
Third use the [Calendar] and set the time and compare the year, month and day of year only. As Dave Webb proposed.
Another approach is to use the "day" part of the epoch value:
Date d = new Date();
Timestamp t = new Timestamp(d.getTime());
long dateEpochDays = d.getTime() % (1000*60*60*24);
long timeStampEpochDays = t.getTime() %(1000*60*60*24);
System.out.println("date: " + dateEpochDays + " timestamp: " + timeStampEpochDays);

Adding Years to a random date from Date class

Let's say I have this:
PrintStream out = System.out;
Scanner in = new Scanner(System.in);
out.print("Enter a number ... ");
int n = in.nextInt();
I have a random date, for example, 05/06/2015 (it is not a fixed date, it is random every time). If I want to take the 'year' of the this date, and add whatever 'n' is to this year, how do i do that?
None of the methods in the Date Class are 'int'.
And to add years from an int, 'years' has to be an int as well.
You need to convert the Date to a Calendar.
Calendar c = Calendar.getInstance();
c.setTime(randomDate);
c.add(Calendar.YEAR, n);
newDate = c.getTime();
You can manipulate the Year (or other fields) as a Calendar, then convert it back to a Date.
This question has long deserved a modern answer. And even more so after Add 10 years to current date in Java 8 has been deemed a duplicate of this question.
The other answers were fine answers in 2012. The years have moved on, today I believe that no one should use the now outdated classes Calendar and Date, not to mention SimpleDateFormat. The modern Java date and time API is so much nicer to work with.
Using the example from that duplicate question, first we need
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
With this we can do:
String currentDateString = "2017-09-12 00:00:00";
LocalDateTime dateTime = LocalDateTime.parse(currentDateString, formatter);
dateTime = dateTime.plusYears(10);
String tenYearsAfterString = dateTime.format(formatter);
System.out.println(tenYearsAfterString);
This prints:
2027-09-12 00:00:00
If you don’t need the time of day, I recommend the LocalDate class instead of LocalDateTime since it is exactly a date without time of day.
LocalDate date = dateTime.toLocalDate();
date = date.plusYears(10);
The result is a date of 2027-09-12.
Question: where can I learn to use the modern API?
You may start with the Oracle tutorial. There’s much more material on the net, go search.
Another package for doing this exists in org.apache.commons.lang3.time, DateUtils.
Date date = new Date();
date = DateUtils.addYears(date, int quantity = 1);
The Date class will not help you, but the Calendar class can:
Calendar cal = Calendar.getInstance();
Date f;
...
cal.setTime(f);
cal.add(Calendar.YEAR, n); // Where n is int
f = cal.getTime();
Notice that you still have to assign a value to the f variable. I frequently use SimpleDateFormat to convert strings to dates.
Hope this helps you.
Try java.util.Calendar type.
Calendar cal=Calendar.getInstance();
cal.setTime(yourDate.getTime());
cal.set(Calendar.YEAR,n);
This will add 3 years to the current date and print the year.
System.out.println(LocalDate.now().plusYears(3).getYear());
If you need add one year a any date use the object Calendar.
Calendar dateMoreOneYear = Calendar.getInstance();
dateMoreOneYear.setTime(dateOriginal);
dateMoreOneYear.add(Calendar.DAY_OF_MONTH, 365);
Try like this as well for a just month and year like (June 2019)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, n); //here n is no.of year you want to increase
SimpleDateFormat format1 = new SimpleDateFormat("MMM YYYY");
System.out.println(cal.getTime());
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
Try this....
String s = new SimpleDateFormat("YYYY").format(new Date(random_date_in_long)); //
int i = Integer.parseInt(s)+n;

Categories

Resources