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.
Related
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
Date date1= new java.util.Date();
java.sql.Date Sqldob = new java.sql.Date(date1.getTime());
System.out.println("date" +Sqldob);
Time Sqldob1 = new Time(date1.getTime());
System.out.println("User Time: " +Sqldob1);
String yourTime="09:30:00";
SimpleDateFormat ra = new SimpleDateFormat("HH:mm:ss");
Date yourDate = ra.parse(yourTime);
Time sqlTime3 = new Time(yourDate.getTime());
System.out.println("your time"+sqlTime3);
if(Sqldob1.before(sqlTime3)){
Sqldob1 = sqlTime3;
System.out.println("inside loop");
}
In the code above I am comparing two time variables for equality, but it is giving me the same value -1 for all the types of input
You need to use the Date#before(Date),Date#after(Date) and Date#equals(Date) methods for basic date comparisons.
E.g:
Date d1 = new Date();
Date d2 = new Date();
if(d1.after(d2)){
// Do something
}
if(d1.before(d2)){
// Do something
}
if(d1.equals(d2)){
// Do something
}
You can use the Date#compareTo(Date) method also, but then, you need to interpret the output of the compareTo method accordingly.
As the docs say:
The value 0 if the argument Date is equal to this Date; a value less
than 0 if this Date is before the Date argument; and a value greater
than 0 if this Date is after the Date argument.
In your case, you are getting -1 because
new SimpleDateFormat("HHH:mm:ss"); is wrong. Should be new SimpleDateFormat("HH:mm:ss");
int compare= sqlTime3.compareTo(Sqldob1); This sqlTime3 has only time in it. The date is the epoch date as you've not mentioned that, and hence, its always going to be before new Date() which is today.
Your solution:- (Hope this addresses your problem)
java.util.Date date1= new java.util.Date();
Time Sqldob1 = new Time(date1.getTime());
System.out.println("User Time: " +Sqldob1);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 19); // Your hour
cal.set(Calendar.MINUTE, 30); // Your Mintue
cal.set(Calendar.SECOND, 00); // Your second
Time sqlTime3 = new Time(cal.getTime().getTime());
System.out.println("your time: "+sqlTime3);
if(Sqldob1.before(sqlTime3)){
Sqldob1 = sqlTime3;
System.out.println("inside loop");
}
You need to parse the date and call methods like before(), after() and equals() like this,
if(date.before(date1)){
System.out.println(" date is before date1 ");
}
if(date.after(date1)){
System.out.println(" date is after date1 ");
}
If both date and date1 are equal you can use equals method,
if(date.equals(date1)){
System.out.println(" date and date1 are equal");
}
Modern version:
LocalDateTime dateTime1 = LocalDateTime.now(ZoneId.systemDefault());
LocalDate dob = dateTime1.toLocalDate();
System.out.println("date " + dob);
LocalTime dob1 = dateTime1.toLocalTime();
System.out.println("User Time: " + dob1);
String yourTime = "09:30:00";
LocalTime time3 = LocalTime.parse(yourTime);
System.out.println("your time " + time3);
if (dob1.isBefore(time3)) {
dob1 = time3;
System.out.println("inside if statement");
}
When I ran this code this morning, it printed:
date 2017-07-07
User Time: 05:32:01.881
your time 09:30
inside if statement
The point is: With the old and now long outdated classes Date and Time it is easy not to get things right. With the modern classes I use here, it’s much easier to get them right.
Are you using java.sql types because you really need to get your date and time from a database and/or store them into one? This was what these were for, you shouldn’t really have used them for other purposes. I use “was” and “were” intentionally because you don’t need them for this purpose either anymore. With a new JDBC driver, you can get a LocalDateTime from the database and store one back, or depending on your column datatype get an Instant and convert it to LocalDateTime:
LocalDateTime dateTime2 = instantFromDb.atZone(ZoneId.systemDefault())
.toLocalDateTime();
PS Item 2. in SoduRahul’s answer gives the real and correct explanation of what went wrong in your program: though Time was meant for time-of-day only, your Sqldob1 ends up holding today’s date and sqlTime3 the date of the epoch (January 1, 1970), so the former will always be after the latter by their before method.
compareTo() method always return zero for equal and non-zero for unequal dates.
I just want to subtract 1 hour from a DateTime I tried looking it up on Google and I found that there is a method called minus that takes a copy of the date and take a specific duration right here: http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#minus(long)
But I don't know how to use it and I can't an find a example on the internet.
Here's my code:
String string1 = (String) table_4.getValueAt(0, 1);
String string2= (String) table_4.getValueAt(0, 2);
DateTimeFormatter dtf = DateTimeFormat.forPattern("hh:mm a").withLocale(Locale.ENGLISH);
DateTime dateTime1 = dtf.parseDateTime(string1.toString());
DateTime dateTime2 = dtf.parseDateTime(string2.toString());
final String oldf = ("hh:mm a");
final String newf= ("hh.mm 0");
final String newf2= ("hh.mm a");
final String elapsedformat = ("hh.mm");
SimpleDateFormat format2 = new SimpleDateFormat(oldf);
SimpleDateFormat format2E = new SimpleDateFormat(newf);
Period timePeriod = new Period(dateTime1, dateTime2);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendHours().appendSuffix(".")
.appendMinutes().appendSuffix("")
.toFormatter();
String elapsed = formatter.print(timePeriod);
table_4.setValueAt(elapsed,0,3);
DecimalFormat df = new DecimalFormat("00.00");
System.out.println(dateTime1);
table_4.setValueAt("", 0, 4);
table_4.setValueAt("", 0, 5);
Sample Data:
dateTime1: 08:00 AM
dateTime2: 05:00 PM
the period will be 9 hours. but i want it to be 8 hrs only because i want to subtract the lunch break in my program.
i tried it with this stupid code:
dateTime1.minus(-1)
I also tried parsing string1 to double so I can subtract it by one.
double strindtoD = Integer.parseInt(string1);
I also tried making another DateTime and use period to get the difference of the two time
String stringOneHour = ("01:00 AM");
DateTime dateTime3 = dtf.parseDateTime(stringOneHour.toString());
Period timePeriod = new Period(dateTime3, dateTime1);
Just use:
dateTime.minusHours(1)
This is documented in the API.
Note that DateTime objects are immutable, so the operation alone has no effect. You need to assign the result of this method to a new object (or replace itself):
dateTime = dateTime.minusHours(1);
As to how to obtain a Period out of the difference between two DateTimes, you must first go through an Interval:
Period period = new Interval(begin, end).toPeriod();
Link to a SO post explaining why there is both Period and Interval.
Side note: Joda Time uses a LOT of indirections in its API; as such reading the Javadoc not only requires one to read the methods for one class, but also look at the list of inherited methods from all the inherited abstract classes/interfaces; for instance, a DateTime is also a ReadableInstant. One you get used to it, though, it's a breeze.
If you are using an older version of org.joda.time.DateTime then you can use minus(ReadablePeriod period) method like this
Date date = LocalDate.now().minus(new Period(1, 0, 0, 0)).toDate();
where Period accepts int hours, int minutes, int seconds, int millis parameters
By using Calender class object you can use this method to subtract hours.
cal.add(Calendar.HOUR_OF_DAY, -numberOfHours);
and also here is complete example link
Ok, so what I'm trying to do is to set the set the date of a calendar instance, and then return the week_of_year. I am doing so by using the Calendar.set() functio
public String weekInYearForm = "ww";
SimpleDateFormat formWIM = new SimpleDateFormat(weekInYearForm, Locale.US);
Calendar lc = Calendar.getInstance();
lc.set(Calendar.YEAR, lYear);
lc.set(Calendar.MONTH, lMonth);
lc.set(Calendar.DAY_OF_MONTH, lDay);
wiy = formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));
To get the lYear, lMonth, and lDay values, I am passing a string in the format 04/26/2013 to through the following steps:
String[] arrDate = dateIn.split("/");
int lMonth = Integer.parseInt(arrDate[0]) - 1;
Log.d("SaveHandler", "Month is: " + lMonth);
int lDay = Integer.parseInt(arrDate[1]);
Log.d("SaveHandler", "Day is: " + lDay);
int lYear = Integer.parseInt(arrDate[2]);
Log.d("SaveHandler", "Year is: " + lYear);
The problem I am facing is that when I look at what is outputed to wiy, it is always 1. Upon some further debugging, I realized that the time is being left at epoch time, and not setting to the values I need.
I also tried using lc.set(lYear, lMonth, lDay), also to no avail. If anyone has any ideas, I would greatly appreciate them.
*EDIT: I did some debugging earlier and it is returning 1970 for the year and 0 for the month.
use
formWIM.format(lc.getTime());
instead of
formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));
EDIT
You can parse your date (instead of dateIn.split( etc.)
SimpleDateFormat monthDayYear = new SimpleDateFormat("MM/dd/yyyy", Locale.US); //04/26/2013
Date date = monthDayYear.parse("04/26/2013");
and then format it
SimpleDateFormat formWIM = new SimpleDateFormat("ww", Locale.US);
formWIM.format(date);
This code is correct, the problem is in formWIM.format(...) or the battery of your motherboard clock is drained.
Let's assume that I have two dates like the following.
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45");
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45");
I want to compare these two dates to see whether firstDate is sooner, later or equal to secondDate.
I could try the following.
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.isBefore(secondDate));
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.isAfter(secondDate));
System.out.println("firstDate = "+firstDate+"\nsecondDate = "+secondDate+"\ncomparison = "+firstDate.equals(secondDate));
What is produced by this code is exactly what I want.
It produces the following output.
firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = true
firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = false
firstDate = 2012-02-16T12:03:45.000+05:30
secondDate = 2013-02-17T12:03:45.000+05:30
comparison = false
I need to ignore the seconds and the milliseconds portion of these dates. I have tried to use the withSecondOfMinute(0) and withMillis(0) methods like the following.
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45").withSecondOfMinute(0).withMillis(0);
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45").withSecondOfMinute(0).withMillis(0);
But it yielded the following output.
firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = false
firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = false
firstDate = 1970-01-01T05:30:00.000+05:30
secondDate = 1970-01-01T05:30:00.000+05:30
comparison = true
The docs of the withSecondOfMinute() method describes.
Returns a copy of this datetime with the second of minute field
updated. DateTime is immutable, so there are no set methods. Instead,
this method returns a new instance with the value of second of minute
changed.
And the docs of the method withMillis() says.
Returns a copy of this datetime with different millis. The returned
object will be either be a new instance or this. Only the millis will
change, the chronology and time zone are kept.
Comparing dates by ignoring the time portion completely can easily be done using DateTimeComparator.getDateOnlyInstance() roughly like the following.
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)==0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)<0){}
if(DateTimeComparator.getDateOnlyInstance().compare(firstDate, secondDate)>0){}
How to compare two dates ignoring the specific instant in DateTime (seconds and milliseconds in this case)?
Another approach is to create a DateTimeComparator with minute as lower limit:
DateTimeComparator comparator = DateTimeComparator.getInstance(
DateTimeFieldType.minuteOfHour());
which would ignore the second and millisecond parts of the objects being compared.
I think you want to use DateTime#withMillisOfSecond() instead of DateTime#withMillis():
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTime firstDate = formatter.parseDateTime("16-Feb-2012 12:03:45").withSecondOfMinute(0).withMillisOfSecond(0);
DateTime secondDate = formatter.parseDateTime("17-Feb-2013 12:03:45").withSecondOfMinute(0).withMillisOfSecond(0);
Setting DateTime#withMillis() to 0, will reset both your dates to 1/1/1970, and hence you get true for equals call on them.
Similarly, setting DateTime#withMillisOfDay() to 0, will set the time to midnight.
public static String getFromatDateTime(Date date) {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime( date );
//gc.set( Calendar.HOUR_OF_DAY, 0 );
//gc.set( Calendar.MINUTE, 0 );
//block ignore second and millisecond
gc.set( Calendar.SECOND, 0 );
gc.set( Calendar.MILLISECOND, 0 );
String strDate = sdfDate.format(gc.getTime());
return strDate;
}
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date now = new Date();
String currentDate = Testing.getFromatDateTime(now);
String fullDate = "2015-12-07 14:53:39.30";
String effDateStr = Testing.getFromatDateTime(sdfDate.parse(fullDate));
System.out.println("Currennt Date: " + currentDate);
System.out.println("Effective Date: " + effDateStr);
System.out.println(currentDate.compareTo(effDateStr)==0);
}