I am calculating time difference between two dates and time but its restuning invalid difference.
here's my sample date and code to calculate the difference.
loginTime=2016-01-24 12:04:30.16
expiryTime = 2016-01-24 13:04:30.16
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date now = new Date();
try {
Date startDate = simpleDateFormat.parse(loginTime);
Date expireDate = simpleDateFormat.parse(expiryTime);
// String temCurrentDate = new SimpleDateFormat("yyyy-MM-dd").format(now);
// Date currentDate = new SimpleDateFormat("yyyy-MM-dd").parse(temCurrentDate);
// String day_of_week = new SimpleDateFormat("EEEE").format(now);
long difference =startDate.getTime()- expireDate.getTime();
int hour = (int) difference / (60 * 60 * 1000);
} catch (ParseException e) {
e.printStackTrace();
}
Difference between this time is 1 hour but i am getting 11 or 13. Please tell where i am going wrong in this.
Spelling error in your variable:
simpleDateFormat.parse(expiryTime);
Does not match: ExpiryTime = 2016-01-24 13:04:30.16
That's the whole problem.
Related
So I have a time range example:
2016-09-26T12:00:00.000+08:00 / 2016-09-27T11:59:00.000+08:00
Assuming the current time is 2016-09-29T06:00:00.000+08:00
So what I want is to get which of dates on the said time range (2016-09-26 or 2016-09-27) the 06:00AM falls...
I tried using joda's Interval class but I can't figure out how to make it work. any suggestion is appreciated.
sample expected outputs:
06:00AM => 2016-09-27
06:00PM => 2016-09-26
03:00AM => 2016-09-27
03:00PM => 2016-09-26
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");
String strEndDate = "2016-09-27T11:59:00.000+0800";
SimpleDateFormat fmt = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:MM:ss.SSSZ");
Date endDate = null;
try {
endDate = fmt.parse(strEndDate);
} catch (Exception e) {
// TODO: handle exception
}
Date currDate = new Date(); // you can set your date and time here
while(currDate.after(endDate)){
currDate.setTime(currDate.getTime()-(24*60*60*1000));
}
String result = fmt.format(currDate);
I think I found a way that works for me
DateTime beginTime = getStartTime();
DateTime withTimeNow = beginTime.withTime(LocalTime.now())
LocalDate result = withTimeNow.isBefore(beginTime)? beginTime.toLocalDate().plusDays(1) : beginTime.toLocalDate();
I'm not sure if it's efficient but it does what I need.
I Have this type of Date in String Format 01-18-2013 06:43:35 Now, i want to compare this Date with Current Date and Time and get Day, Month, Hour, Min, .. I Searched this link but didn't get any Solution...Please share some solution..Thank you..
This might help,
http://developer.android.com/reference/java/text/DateFormat.html
You can parse the Date from string using
DateFormat df = DateFormat.getDateInstance();
myDate = df.parse(myString);
If I get your question, you would like to Compare a Date object with the current date..
Let's say that 'date' is the Date object you want to compare with the current date:
Why don't you just do something like date.after(new Date()) or date.before(new Date()) as suggested form the android doc?
You can get UTC with
new SimpleDateFormat("MM-dd-yyyy HH:mm:ss").parse("01-18-2013 06:43:35").getTime();
Then compare the result with
System.currentTimeMillis();
this may helps you to calculate to diffrent date time in millisecond
try{
Calendar calender = Calendar.getInstance();
Calendar calDb = Calendar.getInstance();
Calendar matchd = Calendar.getInstance();
mYear = calender.get(Calendar.YEAR);
mMonth = calender.get(Calendar.MONTH);
mDay = calender.get(Calendar.DAY_OF_MONTH);
mendYear = calDb.get(Calendar.YEAR);
mendMonth = calDb.get(Calendar.MONTH);
mendDay = calDb.get(Calendar.DAY_OF_MONTH);
// Here you can change day values
calDb.set(Calendar.DAY_OF_MONTH, mDay-1);
strbeforedate = mDateFormat.format(calDb.getTime());
curentdate = mDateFormat.format(calender.getTime());
calDb.setTime(mDateFormat.parse(strbeforedate));
calender.setTime(mDateFormat.parse(curentdate));
String mydate = "2013.03.14 03:11";
String mdatetime = "";
deletepath = new ArrayList<String>();
for(int i=0;i<result.length;i++){
try{
// here your matching goes and pass date here
matchd.setTime(mDateFormat.parse(mdatetime));
long diff = calDb.getTimeInMillis() - calender.getTimeInMillis();
long matchdiff = matchd.getTimeInMillis() - calender.getTimeInMillis();
if(diff < matchdiff){
// do your work here
}else{
// do your else work here
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 2 years ago.
I want to get the date as a year, month ,day without hours or minutes or any thing else, and I don't want to get the year alone and the month and the day each by its self. Because as a full date I need it to comparison with another date
such as today 28.11.2012 and to compare it to 11.12.2011
as if today minus 11.12.2011 more than 280 day I want to execute some code
you can use SimpleDateFormat.
The basics for getting the current date
DateFormat df = new SimpleDateFormat("MMM d, yyyy");
String now = df.format(new Date());
or
DateFormat df = new SimpleDateFormat("MM/dd/yy");
String now = df.format(new Date());
EDITED :
First of All you have the date in String Formate. you have to Convert into date Formate. try below code to do that. you have apply same for both the String strThatDay & strTodaDay you will get Calender Object for both.
String strThatDay = "2012/11/27";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d);
after that try below code to get Day from two Date :
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
try it out. Hope it will help you.
Always use Simpledateformat(yyyy/mm/dd) for comparision..
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String currentDateandTime = sdf.format(new Date());
Use this currentDateandTime to compare with other date.
I think this may be a solution.U have to get instance of 2 calendar (1 for current date and another for compare date.
Calendar cal1=Calendar.getInstance();
Date dt=null;
try{
dt = sdf.parse(currentDateandTime);
cal1.setTime(dt);
}catch (ParseException e){
e.printStackTrace();
}
int currentDaycmp= cal1.get(Calendar.DAY_OF_MONTH);
int currentMonthcmp=cal1.get(Calendar.MONTH);
int currentYearcmp=cal1.get(Calendar.YEAR);
Calendar cal2=Calendar.getInstance();
Date dtend=null;
try{
dtend = sdf.parse(comparedate);
cal2.setTime(dtend);
} catch (ParseException e) {
e.printStackTrace();
}
int currentDayend= cal2.get(Calendar.DAY_OF_MONTH);
int currentMonend=cal2.get(Calendar.MONTH);
int currentyearend=cal2.get(Calendar.YEAR);
now find the difference
currentDaycmp-currentDayend(your condition)..then execute your block..
U try this..May be meet ur requirement..
You may want to use Joda-Time for this:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy");
LocalDate first = LocalDate.parse("28.11.2012", formatter);
// LocalDate first = new LocalDate(2012, 11, 28);
// LocalDate first = LocalDate.now();
LocalDate second = LocalDate.parse("11.12.2011", formatter);
int daysBetween = Days.daysBetween(first, second).getDays();
You should be aware of that daysBetween is a negative value if the second date is before the first like in this example.
For the given example daysBetween is -353.
You can use the compareTo method.
Firstly, make sure that the two dates you are using have the same format. That is, if one is YYYY,DD,MM then the other would be the same.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
Date firstDate = sdf.parse("2012-11-27");
System.out.println(sdf.format(firstDate));
And then you would do a firsDate.compareTo(SecondDate);
if firstDate.compareTo(SecondDate) < 280 {
...
}
Calendar todayCalendar = new GregorianCalendar();
Calendar pickedDateCalendar = new GregorianCalendar();
todayCalendar.set(currentYear,currentMonth,currentDay);
pickedDateCalendar.set(birthDayDatePicker.getYear(),birthDayDatePicker.getMonth(),birthDayDatePicker.getDayOfMonth());
System.out.println("Days= "+daysBetween(todayCalendar.getTime(),pickedDateCalendar.getTime()));
int Days = daysBetween(todayCalendar.getTime(),pickedDateCalendar.getTime());
public int daysBetween(Date d1, Date d2){
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}
i am doing an app that is related to get the age of a person according to the given input of birthday date. for that i am getting the total number of days from that date to the current date from the below code.
String strThatDay = "1991/05/10";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
try {
d = formatter.parse(strThatDay);
Log.i(TAG, "" +d);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis();
long days = diff / (24 * 60 * 60 * 1000);
from this code i am getting total number of days. so my requirement is convert the total number of days in to years ,months and days exactly.. please help....
You should use the Duration class :
Duration duration = new Duration();
duration.add( today );
duration.substract( birthDate);
int years = duration.getYears();
int months = duration.getMonths();
int days = duration.getDays();
Some other alternatives include using a library dedicated to time management : Joda time. See Calculate age in Years, Months, Days, Hours, Minutes, and Seconds
String strThatDay = "1991/05/10";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date thatDate = null;
try {
try {
thatDate = formatter.parse(strThatDay);
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(thatDate);
Calendar toDay = Calendar.getInstance();
toDay.setTime(thatDate);
toDay.add(Calendar.DATE, noOfDays);
int year = toDay.getTime().getYear() - thatDay.getTime().getYear();
int month = toDay.getTime().getMonth() - thatDay.getTime().getMonth();
if(month<0){
year--
month = month+12;
}
int days = toDay.getTime().getDate() - thatDay.getTime().getDate();
if(month<0){
month--
days = days+ toDay.getMaximum(Calendar.MONTH);;
}
I have a code returning me a string (HH:mm).
SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dateObj;
try {
dateObj = curFormater.parse(start);
SimpleDateFormat postFormater = new SimpleDateFormat("HH:mm");
String newDateStr = postFormater.format(dateObj);
startView.setText(newDateStr);
Emission_start = newDateStr;
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.d(" * Error", e.toString());
}
It works great... But right now I would like to:
add x (is dynamically provided) minutes (x = from 5 to 1000 minutes) and transform to time (example time:3:45, add 25 minutes, transform to time 4:10)
Get current time and calculate difference between current time and time from step 1 (4:10)
Get time difference (from step 2) in minutes!
Thanks for your help!
I haven't tested, but something like this should work:
long newDate = dateObj.getTime() +
(x * 60 * 1000)
long diff =
System.currentTimeMillis() - newDate
double diffInMins = diff / (60.0 * 1000.0)
use Calendar
Calendar calInstance = new GregorianCalendar();
calInstance.setTime(dateObj);
Then add any fragment you want, for minutes do
calInstance.add(Calendar.MINUTE, XX)
To, transform use your formatter
postFormatter.format(calInstance.getTime());
is trivial
Diff in minutes can be calculated easily as well
long diffInMins = (currTimeInMillis - calInstance.getTimeInMillis())/(1000 * 60);