i want to compare a date with the current date and do something if the difference is 2 months or 6 or a year .. but i have a problem how to get the correct difference for example if the current month is 02 2015 and the other month is 10 2014 i will get 8 in difference but the actual difference is 4 .. how to do it ?
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat d = new SimpleDateFormat("dd");
SimpleDateFormat m = new SimpleDateFormat("MM");
SimpleDateFormat ye = new SimpleDateFormat("yyyy");
String day = d.format(c.getTime());
String month = m.format(c.getTime());
String year = ye.format(c.getTime());
int d1=Integer.parseInt(day);
int m1=Integer.parseInt(month);
int d2=25;
int m2=02;
int diff=d1-d2;
String s=String.valueOf(diff);
You are calculating your difference between two int, so it can't work.
You should calculate it between two dates or two long (in secondes or milliseconds)
long oneDay, today, delay;
oneDay = 1000*3600*24; //number of milliseconds in a day
today = Calendar.getInstance().getTimeInMillis();
delay = (TheDateYouWantToCompare - today)/oneDay;
if (delay >= 60*oneDay) { //more than 2 months
//your code
}else{
//your code
}
If TheDateYouWantToCompare and today are dates, it's almost the same :
delay = (TheDateYouWantToCompare.getTime() - today.getTime())/oneDay;
Edit :
Here it is how to get time in milliseconds.
String DateString = "31-12-2015";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = sdf.parse(DateString);
long timeInMilliseconds = myDate.getTime();
You could just use the difference in milliseconds between the 2 dates. Pre-compute the differences you need/want as constants and compare to the delta you have, for example:
static final long DAY = 1000 * 60 * 60 * 25;
static final long MONTH = DAY * 30;
...
int diff = d1 - d2;
if(diff > MONTH) {
//more than a month difference
}
If you need something more complex you should perhaps use a library such as Joda Time which will give a more comprehensive set of features to work with time.
Related
Time 1 : 10:30 06/05/2018
Time 2 : 19:45 06/05 2018
I want to pick a random time between these two time. The result may be (13:15 06/05/2018).
I look into Calendar but seem it does not support a method like range(time1, time2)
What is the solution for this case ? Thanks.
I would use something like this.
public static Calendar getRandomTime(Calendar begin, Calendar end){
Random rnd = new Random();
long min = begin.getTimeInMillis();
long max = end.getTimeInMillis();
long randomNum = min + rnd.nextLong()%(max - min + 1);
Calendar res = Calendar.getInstance();
res.setTimeInMillis(randomNum);
return res;
}
if you have API 21+, use ThreadLocalRandom
public static Calendar getRandomTime(Calendar begin, Calendar end){
long randomNum = ThreadLocalRandom.current().nextLong(begin.getTimeInMillis(), end.getTimeInMillis() + 1);
Calendar res = Calendar.getInstance();
res.setTimeInMillis(randomNum);
return res;
}
you should convert your times objects to long first as follows (I suppose that you have two Calendar objects already)
long time1InLong = time1.getTimeInMillis();
long time2InLong = time2.getTimeInMillis();
Then you can use following code to generate random number
Random r = new Random();
long randomTime = r.nextLong(time2InLong - time1InLong) + time1InLong;
Then you can convert this randomTime back to Calendar as follows
// Create a DateFormatter object for displaying date in specified format.
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm dd/MM/yyyy");
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(randomTime);
I'm trying to parse time only but the app code includes the date and the year.
here is my code:
simpleDateFormat2 = new SimpleDateFormat("HH:mm");
int h = Integer.parseInt(traffic.alarmClocks.get(0).get(ApplicationConstants.HOUR));
int m = Integer.parseInt(traffic.alarmClocks.get(0).get(ApplicationConstants.MINUTE));
String datex2 = h + ":" + m;
Date storedalarm = simpleDateFormat2.parse(datex2);
output of the datex2 is : 4:56
Output of StoredAlarm is this: http://imgur.com/a/UVpbh
The output of the datex2 is correct, but I need to make it into date because I am going to use it to compare times.
you just need to compare times you could very easily combine hours and minutes this way:
int time = hours * 60 + minutes;
then you could just compare 2 integers.
or if you really want a Date object, you could initialize it with year, month and date to 0, and just pass hours and minutes
Date storedalarm = new Date(0, 0, 0, h, m);
in order to show just hours and minutes from your Date object you can use the same SimpleDateFormat you instantiated before
String formattedDate = simpleDateFormat2.format(storedalarm);
I need to output the difference between 2 dates in years, months and days.
in my code when subtract two or three days from 1 year it gives wrong output
like remaining year,month,days is 0 year / 12 month /3 days
This is what I do.
Date date = null, date1 = null;
try {
date = formatter.parse(SharedPreference.getWeddingDate(getActivity()));
date1 = formatter.parse(getCurrentTimeStamp());
targetTime = new GregorianCalendar();
targetTime.setTime(date);
currentTime = new GregorianCalendar();
currentTime.setTime(date1);
}
catch (ParseException e) {
e.printStackTrace();
}
long timeOne = date.getTime();
long timeTwo = date1.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
int year = (int) (delta / 365);
int rest = (int) (delta % 365);
int month = rest / 30;
rest = rest % 30;
Unfortunately the stuff around java.util.Calendar does not give you any support for the calculation of durations. I know three external libraries available on Android platform which can do this much better and save you some headache. Internally the calculation is not so simple as some people want to make you believe. For example timezones are involved, too.
// input
String tz = "Europe/Paris";
java.util.Date d1 = new java.util.Date(0); // or: SharedPreference.getWeddingDate(getActivity());
java.util.Date d2 = new java.util.Date();
// library Threeten-ABP (similar but not identical to Java-8)
LocalDate start = Instant.ofEpochMilli(d1.getTime()).atZone(ZoneId.of(tz)).toLocalDate();
LocalDate end = Instant.ofEpochMilli(d2.getTime()).atZone(ZoneId.of(tz)).toLocalDate();
Period p = Period.between(start, end);
System.out.println(p.getYears()); // 45
System.out.println(p.getMonths()); // 11
System.out.println(p.getDays()); // 3
System.out.println(p); // P45Y11M3D
// Joda-Time-Android
DateTimeZone dtz = DateTimeZone.forID(tz);
org.joda.time.LocalDate jd1 = new org.joda.time.LocalDate(d1, dtz);
org.joda.time.LocalDate jd2 = new org.joda.time.LocalDate(d2, dtz);
org.joda.time.Period jp = new org.joda.time.Period(jd1, jd2, PeriodType.yearMonthDay());
System.out.println(jp.getYears()); // 45
System.out.println(jp.getMonths()); // 11
System.out.println(jp.getDays()); // 3
System.out.println(jp); // P45Y11M3D
// my library Time4A
PlainDate date1 = TemporalType.JAVA_UTIL_DATE.translate(d1).toZonalTimestamp(tz).toDate();
PlainDate date2 = TemporalType.JAVA_UTIL_DATE.translate(d2).toZonalTimestamp(tz).toDate();
Duration<CalendarUnit> duration = Duration.inYearsMonthsDays().between(date1, date2);
System.out.println(duration.getPartialAmount(CalendarUnit.YEARS)); // 45
System.out.println(duration.getPartialAmount(CalendarUnit.MONTHS)); // 11
System.out.println(duration.getPartialAmount(CalendarUnit.DAYS)); // 3
System.out.println(duration); // P45Y11M3D
If your wedding date input is in the future then just swap start and end in between-calculations in order to avoid negative durations.
I am writing an application in which I have to display a date . Now I want to convert that date into Year and Month from the Current Date.
My Date is Like - 29/03/2017.
I want to convert this date into Year and Months.
Sorry I think you are not able to understand my question. I want the Difference of current date and above date in year and months.
Sorry for my explanation.
You can use Joda Time and compute a Period between two LocalDate values (which is what you've got here) using months and years as the units.
example
LocalDate dob = new LocalDate(1992, 12, 30);
LocalDate date = new LocalDate(2010, 12, 29);
Period period = new Period(dob, date, PeriodType.yearMonthDay());
System.out.println(period.getYears() + " years and " +
period.getMonths() + " months");
I found my answer using Calender class .
First i find the difference between two days and using that days i found the years and months.
Here i post my code, which i think help to others.
int days = Integer.parseInt(Utility.getDateDiffString("29/03/2017"));
int years = days/365;
int remainingDays = days - (365*years);
int months = remainingDays/30;
getDateDiffString() Method. In this method we need to pass end date
public static String getDateDiffString(String endDate)
{
try
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dateTwo = dateFormat.parse(endDate);
long timeOne = cal.getTimeInMillis();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "" + delta + "";
}
else {
delta *= -1;
return "" + delta + "";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
if your date's format is fixed, you can do it like this :
String myDate = "29/03/2017";
String newDate = myDate.subString(6, 10) + "-" + myDate.subString(3, 5)
this method to convert the normal string to date format
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("mm/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
after that you get the formal method
You Should use SimpleDateFormate !
For Example:--- You can get time & Date as you want:-
Date email_date = m.getSentDate();// this is date which you are getting
DateFormat date = new SimpleDateFormat("EEE MMM yyyy");
DateFormat time = new SimpleDateFormat("hh:mm aa");
String date_str=date.format(email_date);
String time_str=time.format(email_date);
Use Java Calendar class to get year from date
Calendar c=Calendar.getInstance();
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy MMM");
System.out.println(simpleDateformat.format(c.getTime()));
To get difference between two date
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
long timeDiff = (d1.getTime() - d2.getTime());
String diff=String.format("%d year(s) %d day(s) %d hour(s) %d min(s) %d sec(s)",(TimeUnit.MILLISECONDS.toDays(timeDiff)/365),TimeUnit.MILLISECONDS.toDays(timeDiff)%365,
TimeUnit.MILLISECONDS.toHours(timeDiff)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS
.toDays(timeDiff)),
TimeUnit.MILLISECONDS.toMinutes(timeDiff)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(timeDiff)));
System.out.println(diff);
Specify correct date here in d1 & d2.Then you will get right answer of difference
First put your Date into a String variable as:
String dateToConvert = "29/03/2017";
Instantiate Calendar as:
Calendar convertedDate = Calendar.getInstance();
Set that date to calendar
convertedDate.set(dateToConvert);<br/>
Then use this line:
String datePicked = DateFormat.getDateInstance().format(convertedDate.getTime());
Output: Mar 29, 2017
I'm trying to generate a random month and year with an upper bound of the current year and month and a lower bound that will be a static month and year.
I can generate the year with:
int randomYear = (int) (Math.random() * ( currentYear - 2000 ))+2000;
//returns a val 2000-2012
Where 2000 is my lower bound. So hypothetically that would generate a year between 2012-2000. The problem I run into is when I try to set a month I'm not sure how to handle if the random generator returns 2012 and there is only 2 months. Currently I have:
int randomMonth = (int) Math.random() * (12);
How do I handle the special cases such as the case with 2012 or if I set the lower bounds for a year 2000 and a month of 10?
This might seems a little bit long to you, but it's much nicer to work with actual dates:
public static void main(String[] args) {
Calendar now = Calendar.getInstance();
Calendar min = Calendar.getInstance();
Calendar randomDate = (Calendar) now.clone();
int minYear = 2012;
int minMonth = 2;
int minDay = 18;
min.set(minYear, minMonth-1, minDay);
int numberOfDaysToAdd = (int) (Math.random() * (daysBetween(min, now) + 1));
randomDate.add(Calendar.DAY_OF_YEAR, -numberOfDaysToAdd);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(dateFormat.format(now.getTime()));
System.out.println(dateFormat.format(min.getTime()));
System.out.println(dateFormat.format(randomDate.getTime()));
}
public static int daysBetween(Calendar from, Calendar to) {
Calendar date = (Calendar) from.clone();
int daysBetween = 0;
while (date.before(to)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
System.out.println(daysBetween);
return daysBetween;
}
//edit: puh.. harder than I thought ;) But that's it.
Why not use unix timestamps - find the current time as a timestamp and the start time as a timestamp.
Now you have two integers, and it'll be easy to pick a random integer between them and convert it back into a proper date/time.