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

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

Related

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

Get the Difference between 2 Times [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
i'm trying the get the Difference between 2 dates time..
i have an arraylist, each object contains data of type Date..
My Questions are:
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date & Time
2) should i fill manually the data in variable of Date, as follows:
Date currentDate = new Date();
currentDate.setMinutes(Calendar.getInstance().get(Calendar.MINUTE));
currentDate.setHours(Calendar.getInstance().get(Calendar.HOUR));
currentDate.setDate(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
currentDate.setMonth(Calendar.getInstance().get(Calendar.MONTH));
currentDate.setYear(Calendar.getInstance().get(Calendar.YEAR));
3) How to get the Difference between the currentDate and the an old date i have
is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date
JavaDoc from java.util.Date empty constructor:
Allocates a Date object and initializes it so that it represents the
time at which it was allocated, measured to the nearest millisecond.
3) How to get the Difference between the currentDate and the an old date i have is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
Date oldDate = ...
Date currentDate = new Date();
long dt = currentDate.getTime() - oldDate.getTime();
1) To get the current date:
Date = new Date();
2) TO set manually a Date it is better to work with a Calendar.
Calendar c = new GregorianCalendar();
c.set(Calendar.MONTH, 1);
c.set(Calendar.YEAR, 2015);
// ... and so on
Date date = c.getTime();
3) to calculate the distance in ms between two dates.
Date d1 = ....;
Date d2 = ....;
long distance = d1.getTime() - d2.getTime();
Try this, variable now below is current date.
String givenDate = "03/11/2015";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = (Date)dateFormat.parseObject(givenDate);
Date now = new Date();
System.out.println(date);
System.out.println(now);
int diffInDays = (int)( (now.getTime() - date.getTime())
/ (1000 * 60 * 60 * 24) );
System.out.println(diffInDays);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can choose any format and add time or AM/PM, see more details of SimpleDateFormat. If you dont have string dates then you can directly use date variable shown above.
Cheers !!

converting a date string into milliseconds in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calculate date/time difference in java
how would a future date such as Sat Feb 17 2012 be converted into milliseconds in java that can then be subtracted from the current time in milliseconds to yield time remaining until that future date.
The simplest technique would be to use DateFormat:
String input = "Sat Feb 17 2012";
Date date = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long milliseconds = date.getTime();
long millisecondsFromNow = milliseconds - (new Date()).getTime();
Toast.makeText(this, "Milliseconds to future date="+millisecondsFromNow, Toast.LENGTH_SHORT).show();
A more difficult technique (that basically does what DateFormat does for you) involves parsing it yourself (this would not be considered best practice):
String input = "Sat Feb 17 2012";
String[] myDate = input.split("\\s+");
int year = Integer.parseInt(myDate[3]);
String monthString = myDate[1];
int mo = monthString.equals("Jan")? Calendar.JANUARY :
monthString.equals("Feb")? Calendar.FEBRUARY :
monthString.equals("Mar")? Calendar.MARCH :
monthString.equals("Apr")? Calendar.APRIL :
monthString.equals("May")? Calendar.MAY :
monthString.equals("Jun")? Calendar.JUNE :
monthString.equals("Jul")? Calendar.JULY :
monthString.equals("Aug")? Calendar.AUGUST :
monthString.equals("Sep")? Calendar.SEPTEMBER :
monthString.equals("Oct")? Calendar.OCTOBER :
monthString.equals("Nov")? Calendar.NOVEMBER :
monthString.equals("Dec")? Calendar.DECEMBER : 0;
int day = Integer.parseInt(myDate[2]);
Calendar c = Calendar.getInstance();
c.set(year, mo, day);
long then = c.getTimeInMillis();
Time current_time = new Time();
current_time.setToNow();
long now = current_time.toMillis(false);
long future = then - now;
Date d = new Date(future);
//TODO use d as you need.
Toast.makeText(this, "Milliseconds to future date="+future, Toast.LENGTH_SHORT).show();
Firts, you must parse you String to get its Date representation. Here are examples and some docs.
Then you shoud call getTime() method of your Date.
DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
long futureTime = 0;
try {
Date date = format.parse("Sat Feb 17 2012");
futureTime = date.getTime();
} catch (ParseException e) {
Log.e("log", e.getMessage(), e);
}
long curTime = System.currentTimeMillis();
long diff = futureTime - curTime;
Pass year, month and day of the future date in the date of this code and variable diff will give the millisecond time till that date,
Date date = new GregorianCalendar(year, month, day).getTime();
Date today = new Date();
long diff = date.getTime() - today.getTime();
You can simply call the getTime() method of date object. please follow through the sample below
import java.util.Date;
public class Test {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
System.out.println(new Date("Sat Feb 17 2012").getTime());
}
}
try { String str_date="11-June-07";
SimpleDateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MMM-yy");
date = (Date) formatter.parse(str_date);
Log.i("test",""+date);
} catch (Exception e)
{System.out.println("Exception :"+e); }
Date d = new Date();
long time = d.getTime();
long timeDiff = time - lastTime;
//timeDiff will contain your value.
//import these two,
//import java.text.SimpleDateFormat;
//import java.util.Date;

I have a date in(string) in dd-mon-yyyy format and I want to compare this date with system date

I have a date in(string) in dd-mon-yyyy format and I want to compare this date with system date.
eg.
I have 12-OCT-2010
and I want to compere this with system date in same format
You can use the SystemDateFormat class to parse your String, for example
final DateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
final Date input = fmt.parse("12-OCT-2010");
if (input.before(new Date()) {
// do something
}
Note that SimpleDateFormat is not threadsafe, so needs to be wrapped in a ThreadLocal if you have more than one thread accessing your code.
You may also be interested in Joda, which provides a better date API
Use SimpleDateFormat http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
String d = "12-OCT-2010";
try {
Date formatted = f.parse(d);
Date sysDate = new Date();
System.out.println(formatted);
System.out.println(sysDate);
if(formatted.before(sysDate)){
System.out.println("Formatted Date is older");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I would recommend using Joda Time. You can parse that String into a LocalDate object very simply, and then construct another LocalDate from the system clock. You can then compare these dates.
Using simpledateformat -
String df = "dd-MMM-yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(df);
Calendar cal = Calendar.getInstance();
/* system date */
String systemdate = sdf.format(cal.getTime());
/* the date you want to compare in string format */
String yourdate = "12-Oct-2010";
Date ydate = null;
try {
ydate = sdf.parse(yourdate);
} catch (ParseException e) {
e.printStackTrace();
}
yourdate = sdf.format(ydate);
System.out.println(systemdate.equals(yourdate) ? "true" : "false");

Categories

Resources