Comparing two time for a fixed difference in java - 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");

Related

Check if this date transcend one minute of new date

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);

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..

how to get years, months and days from date of birth in java [duplicate]

I have a Date object in Java stored as Java's Date type.
I also have a Gregorian Calendar created date. The gregorian calendar date has no parameters and therefore is an instance of today's date (and time?).
With the java date, I want to be able to get the year, month, day, hour, minute, and seconds from the java date type and compare the the gregoriancalendar date.
I saw that at the moment the Java date is stored as a long and the only methods available seem to just write the long as a formatted date string. Is there a way to access Year, month, day, etc?
I saw that the getYear(), getMonth(), etc. methods for Date class have been deprecated. I was wondering what's the best practice to use the Java Date instance I have with the GregorianCalendar date.
My end goal is to do a date calculation so that I can check that the Java date is within so many hours, minutes etc of today's date and time.
I'm still a newbie to Java and am getting a bit puzzled by this.
Use something like:
Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
// etc.
Beware, months start at 0, not 1.
Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.
With Java 8 and later, you can convert the Date object to a LocalDate object and then easily get the year, month and day.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
Note that getMonthValue() returns an int value from 1 to 12.
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("MMMM");
System.out.println("MONTH "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("YYYY");
System.out.println("YEAR "+simpleDateFormat.format(date).toUpperCase());
EDIT: The output for date = Fri Jun 15 09:20:21 CEST 2018 is:
DAY FRIDAY
MONTH JUNE
YEAR 2018
You could do something like this, it will explain how the Date class works.
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
String yourDateString = "02/28/2012 15:00:00";
SimpleDateFormat yourDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date yourDate = yourDateFormat.parse(yourDateString);
if (yourDate.after(currentDate)) {
System.out.println("After");
} else if(yourDate.equals(currentDate)) {
System.out.println("Same");
} else {
System.out.println("Before");
}
private boolean isSameDay(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
return (sameDay && sameMonth && sameYear);
}
It might be easier
Date date1 = new Date("31-May-2017");
OR
java.sql.Date date1 = new java.sql.Date((new Date()).getTime());
SimpleDateFormat formatNowDay = new SimpleDateFormat("dd");
SimpleDateFormat formatNowMonth = new SimpleDateFormat("MM");
SimpleDateFormat formatNowYear = new SimpleDateFormat("YYYY");
String currentDay = formatNowDay.format(date1);
String currentMonth = formatNowMonth.format(date1);
String currentYear = formatNowYear.format(date1);
Date queueDate = new SimpleDateFormat("yyyy-MM-dd").parse(inputDtStr);
Calendar queueDateCal = Calendar.getInstance();
queueDateCal.setTime(queueDate);
if(queueDateCal.get(Calendar.DAY_OF_YEAR)==Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
{
"same day of the year!";
}
#Test
public void testDate() throws ParseException {
long start = System.currentTimeMillis();
long round = 100000l;
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay(new Date());
}
long mid = System.currentTimeMillis();
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay2(new Date());
}
long end = System.currentTimeMillis();
System.out.println(mid - start);
System.out.println(end - mid);
}
public static Date getYearMonthDay(Date date) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyyyMMdd");
String dateStr = f.format(date);
return f.parse(dateStr);
}
public static Date getYearMonthDay2(Date date) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
return c.getTime();
}
public static int compare(Date today, Date future, Date past) {
Date today1 = StringUtil.getYearMonthDay2(today);
Date future1 = StringUtil.getYearMonthDay2(future);
Date past1 = StringUtil.getYearMonthDay2(past);
return today.compare // or today.after or today.before
}
getYearMonthDay2(the calendar solution) is ten times faster. Now you have yyyy MM dd 00 00 00, and then compare using date.compare

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);

How to find the difference between two times in Android / Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
i have two date values in two textboxes in string datatypes in HH:MM:SS format.HOw can i find difference between them and get result in HH:MM:SS?please help me...as fast as possible....!
Try this:
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date date1 = (Date) format.parse("4:15:20");
Date date2 = (Date) format.parse("2:30:30");
//time difference in milliseconds
long timeDiff = date1.getTime() - date2.getTime();
//new date object with time difference
Date diffDate = new Date(timeDiff);
//formatted date string
String timeDiffString = format.format(diffDate);
System.out.println("Time Diff = "+ timeDiffString );
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above code has certain limitations. Other proper way could be to convert the long value of time difference manually in the string as below:
long timeDiffSecs = timeDiff/1000;
String timeDiffString = timeDiffSecs/3600+":"+
(timeDiffSecs%3600)/60+":"+
(timeDiffSecs%3600)%60;
System.out.println("Time Diff = "+ timeDiffString);
The code you have will give you the number of milliseconds difference between the listed dates. It could be that the answer could be simply divide by 1000 to get the number of seconds.
First Convert String date into simple Date formate
public String getconvertdate1(String date)
{
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
Date parsed = new Date();
try
{
parsed = inputFormat.parse(date);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String outputText = outputFormat.format(parsed);
return outputText;
}
//now can do anything with date.
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);// you get day difference between
AND use simpledateFormate to configure HH:MM:SS

Categories

Resources