Check if this date transcend one minute of new date - java

Problem
how can i do a condition that check if dateReservation transcend one minute of new date!!!
Code
Adresse entity = adresseDao.findOne(id);
entity.setStatut("RESERVER");
entity.setDateReservation(new Date());
Date date1 = entity.getDateReservation();
Date date2 = new Date();
entity.setReserverPar(secUtilisateurService.getCurrentUser());
adresseDao.save(entity);

if(date1.getTime() >= (date2.getTime() + TimeUnit.MINUTES.toMillis(1))){
....
}
could be a simple approach. This basically checks the reservation time is equal or greater than 1 minute after current time. The comparison is done on milliseconds.
There could be more ways to do this, depending on the libraries and java version you have.

try this
try {
SimpleDateFormat fmt = new SimpleDateFormat(DATE_YYYY_MM_ddTHH_MM_SS_Z);
Date date1 = fmt.parse(entity.getDateReservation());
Date date2 = new Date();
// Calculates the difference in milliseconds.
long millisDiff = nowDate.getTime() - date1.getTime();
int minutes = (int) (millisDiff / 60000 % 60);
if( minutes<1 && minutes>=0)
return true;
else
//what you want if false;
} catch (Exception e) {
// log exception
}
...it could also be convenient to write the possible exception in a log. Hi!

// thank you so much That's what I did
Date date1 = adresse.getDateReservation();
Date date2 = new Date();
long millisDiff = (date2.getTime() - date1.getTime());
long minutes = (long) (millisDiff / (60000));
if(minutes > 1){
adresse.setStatut(EnumStatutAdresse.LIBRE.toString());
adresse.setReserverPar(null);
}
adresseDao.save(adresse);

Related

I want to get time difference between two time in milisecond

I want to get time difference between two times in milliseconds.
Note
If the difference is above half a second they return 1000 millisecond, so how to get
proper millisecond like if difference of half second to get 500 millisecond
Difference between two times is half second then my code returns
1000 milliseconds that means 1 Second but actually its 0.5 Second so how get 500
milliseconds if difference is half second
Date Date1 = sdf.parse(lastTime);
Date Date2 = sdf.parse(sdf.format(Calendar.getInstance().getTime()));
long millie = Date2.getTime() - Date1.getTime();
SimpleDateFormat does not include milliseconds by default. So
sdf.format(Calendar.getInstance().getTime());
does not output the milliseconds and everything is rounded to seconds.
Define a custom date format including milliseconds like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ\"");
If you use java8 then try with this:
LocalDateTime startTime = LocalDateTime.of(2018,07,31,12,1);
long diff = ChronoUnit.MILLIS.between(startTime,LocalDateTime.now());
you can find difference between two date in millisecond,second,minutes and hours by calling following method, you can change method by your requirements.
public void printDifference(Date startDate) {
Date endDate=new Date();
long different = endDate.getTime() - startDate.getTime(); //Different in miliseconds
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
int months=0,year=0;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
}
try my below code:
Date date = null;
String value="3 Feb 2018 13:01:41 GMT";
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
date = formatter.parse(value);
} catch (Exception e) {
e.printStackTrace();
}
// Prints the date in the CET timezone
System.out.println("ConvertTime from serverformat before settimezone ::" + formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getDefault());
// Prints the date in the IST timezone
System.out.println("ConvertTime from serverformat after settimezone ::" + formatter.format(date));
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date dateobj = new Date();
System.out.println("Current date and time before settimezone:: " + df.format(dateobj));
df.setTimeZone(TimeZone.getDefault());
System.out.println("current format after settimezone ::" + df.format(dateobj));
int difference = 0;
int diff_Minutes=0;
int diff_Seconds=0;
System.out.println("Default values::" + difference+" "+diff_Minutes+" "+diff_Seconds);
difference = (int) (dateobj.getTime() - date.getTime());
diff_Minutes = difference / (60 * 1000) % 60;
diff_Seconds = difference / 1000 % 60;
here i am converting current time from server time . here u have to take difference between two times. i hope you understand above code.let me know is it ok or not...
Thanks.

Check between two datetime if passed in Java/Android

I have two date time string, one is current time and second is given as follows.
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
Now I want to check if the endTime has passed currentTime.
Thanks
Take a look at
this and this
Example:
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyyHH:mm:ss");
try {
Date currentTimeDate = sdf.parse("05/30/2018 16:56:21");
Date endTimeDate = sdf.parse("05/30/2018 16:59:21");
currentTimeDate.compareTo(endTimeDate); // false / current time has not passed end time.
endTimeDate.compareTo(currentTimeDate); // true / end time has passed current time.
} catch (ParseException ignored) {
}
Convert both strings to Date object and then use before() method to check if the end time has passed currentTime.
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
Date current=new SimpleDateFormat("dd/MM/yyyy").parse(currentTime);
Date end=new SimpleDateFormat("dd/MM/yyyy").parse(endTime);
if(end.before(current)) {
// end time has passed currenctTime
} else {
// no
}
Keep both times in milliseconds which is a long value
long currentTime= System.currentTimeMillis();
You can also convert your and time in millies using below code.
String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
Date mDate = sdf.parse(givenDateString);
long endTime= mDate.getTime();
System.out.println("Date in milli :: " + endTime);
} catch (ParseException e) {
e.printStackTrace();
}
Now compare, if current time is larger then end time, thus current time has passed end time like below.
if(currentTime>endTime){
//Do stuff
}
Enjoy..

Calculate no of days between two dates in java [duplicate]

This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);

Comparing two time for a fixed difference in java

I have my code
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date curDate = new Date();
String finalCurTime=format.format(curDate).substring(11, 19);
Date gpsLastDate = new Date(gpslastKnownLocation.getTime());
String gpsFinalLastTime=format.format(gpsLastDate).substring(11, 19);
How can i compare to below Logic
Compare finalCurTime & gpsFinalLastTime
If(If finalCurTime is more than three hours of gpsFinalLastTime)
{
// Do something-1
}else{
// Do something-2
}
Use Date.getTime() to get the time in milliseconds.
// If the difference in milliseconds is larger than 3 hours in milliseconds
if (curDate.getTime() - gpsLastDate.getTime() > 10800000) {
// Do something-1
} else {
// Do something-2
}
Calendar calendarobj = Calendar.getInstance();
calendarobj.setTime(gpsLastDate);
int hour = calendarobj.get(Calendar.HOUR);
if(hour>3)
System.out.println("greater");

I want difference between two date in java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
how to calculate difference between two dates using java
I have try to difference two date by using some example but I have not got correct answer.
java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
java.util.Date date1 = df.parse("2012-09-14 15:26:14+00");
java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
long diff = Math.abs(date2.getTime() - date1.getTime());
System.out.println("millisecond="+diff);
I want month difference also but it didnt gave me. It is giving me difference days,hours,minute and seconds but not month.What am i doing wrong? Please help me
Edit:
java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
java.util.Date date1 = df.parse("2012-09-30 15:26:14+00");
java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
long diff = Math.abs(date2.getTime() - date1.getTime());
System.out.println(date2.getTime()+"date2");
System.out.println(date1.getTime()+"date1");
System.out.println("millisecond="+diff);
diff=diff/1000;
System.out.println("second="+diff);
long days=diff/86400;
days=days%86400;
long hours=diff/3600;
hours=hours%3600;
long min=diff/60;
min=min%60;
hours=(hours-(24*days));
String time=days+":"+hours+":"+min;
System.out.println(time);
System.out.println("days="+days+":"+"hours="+hours+":"+"minutes"+min);
This is what i am trying to do.
You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.
Sample snippet for time-diff:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
call it as getDuration(date1, date2, Calendar.MONTH);
public static long getDuration(Date returnTime, Date leaveTime, int scale) {
long durationInMillis = returnTime.getTime() - leaveTime.getTime();
switch (scale) {
case Calendar.MINUTE:
return durationInMillis / ONE_MINUTE_IN_MILLIS;
case Calendar.MILLISECOND:
return durationInMillis;
case Calendar.SECOND:
return durationInMillis / ONE_SECOND_IN_MILLIS;
case Calendar.HOUR:
return durationInMillis / ONE_HOUR_IN_MILLIS;
case Calendar.DAY_OF_YEAR:
case Calendar.DATE:
return durationInMillis / ONE_DAY_IN_MILLIS;
case Calendar.MONTH:
return durationInMillis / ONE_MONTH_IN_MILLIS; // 30days per month
}
throw new IllegalArgumentException("invalid scale specified");
}
Date.getTime returns milliseconds, not seconds. You need to divide by 1000 to get seconds.
long diff = Math.abs(date2.getTime() - date1.getTime()) / 1000;
Also as mentioned in the comments your format string is incorrect. It should be this:
"yyyy-MM-dd HH:mm:ss"
The difference you're getting there is the number of milliseconds between the two dates, not seconds. Note that the difference between the dates you've given is not a full month.
To start with let's change yyyy-mm-dd hh:mm:ss to yyyy-MM-dd HH:mm:ss.
The difference between dates can be calculated only with Calendar class and below is my Calendar based solution, not sure it's the best one but it is definitely doing its job. It calculates the dates difference in fill months, that is 2012-09-30 15:26:14+00 - 2012-08-30 15:26:14+00 is 1 month. But 2012-09-30 15:26:14+00 - 2012-08-30 15:26:15+00 is 0 month.
Note that Locale also matters, because the result depends on light saving setting.
I will not comment on it in the hopes that everything is clear from the code
public static void main(String[] args) throws Exception {
java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date1 = df.parse("2012-09-30 15:26:14+00");
java.util.Date date2 = df.parse("2012-08-30 15:26:14+00");
int diff = getMonthDifference(date1, date2);
System.out.println(diff);
}
.
public static int getMonthDifference(java.util.Date date1, java.util.Date date2) {
if (date1.after(date2)) {
return getMonthDifference0(date1, date2);
} else if (date2.after(date1)) {
return -getMonthDifference0(date2, date1);
}
return 0;
}
.
private static int getMonthDifference0(java.util.Date date1, java.util.Date date2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(date1);
c2.setTime(date2);
int diff = 0;
while (c2.getTimeInMillis() < c1.getTimeInMillis()) {
c2.add(Calendar.MONTH, 1);
diff++;
}
int dd = c2.get(Calendar.DAY_OF_MONTH) - c1.get(Calendar.DAY_OF_MONTH);
if (dd > 0) {
diff--;
} else if (dd == 0) {
int hd = c2.get(Calendar.HOUR_OF_DAY) - c1.get(Calendar.HOUR_OF_DAY);
if (hd > 0) {
diff++;
} else if (hd == 0) {
long t1 = c1.getTimeInMillis() % (60 * 1000);
long t2 = c2.getTimeInMillis() % (60 * 1000);
if (t2 > t1) {
diff--;
}
}
}
return diff;
}

Categories

Resources