Calendar class: set to ten days from now - java

I have the following two methods:
private long getTimeInMilliseconds()
{
Calendar c = Calendar.getInstance();
if(c.get(Calendar.DAY_OF_MONTH) == 21)
{
c.set(Calendar.MONTH, Calendar.MONTH + 1 );
c.set(Calendar.DAY_OF_MONTH, 1);
}
else
c.set(Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH + 10);
if(c.get(Calendar.MONTH) > 11)
c.set(Calendar.MONTH, 0);
return c.getTimeInMillis();
}
public static void remainingTime(L2PcInstance player)
{
long now = System.currentTimeMillis();
long then = player.getExpBoostTime();
long time = then - now;
int hours = (int) (time / 3600000);
player.sendMessage(hours+ " hours remaining until your EXP BOOST PERIOD ends");
}
I want getTimeInMillisSeconds() to return the time 10 days later. I want remainingTime() to show how many days (in hours) remain.
With the code above, it shows 4 days remaining and not 10.
Can anybody help?

You are making a mistake in the set() method.
It should be
c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 10);
However, your approach is far from being the best. The one suggested in another answer (adding 10 * 24 * 60 * 60 * 1000 milliseconds to the current time) is far better IMHO.

The best way to get "ten days from now" is to use timestamps/milliseconds.
You can get the current time in milliseconds from a calendar like this:
Calendar someCalendar = new Calendar();
long someTimestamp = someCalendar.getTimeInMillis();
Once you get that, you can add ten days to it (again in milliseconds):
long tenDays = 1000 * 60 * 60 * 24 * 10;
long tenDaysFromNow = someTimestamp + tenDays;

Related

Finding the difference between a time and the current time

So I'm writing an app that has similar functionality to an alarm clock. It asks for the user to input a time. But I've been stuck on how to figure this out for a while.
The method needs to find the difference in minutes between the user selected time, and the current time. Assuming that the user will always put in a time that is AFTER the current time (otherwise it wouldn't make sense to use my app), the difference would just be (userTimeInMins - currTimeInMins), where both are calculated by ((hours * 60) + minutes).
BUT. Here's the problem:
Ex 1) If the current time is 10 PM, and the user enters in the time 2 AM. The above algorithm would say that the difference between the two times is (22 * 60 + 0) - (2 * 60 + 0), which is clearly incorrect because this would mean there is a difference of 20 hours between 10PM and 2 AM, when the difference is actually 4 hours.
Ex 2) If the current time is 1PM, and the user enters in the time 2AM. The above algorithm would say that the difference between the two times is (13 * 60 + 0) - (2 * 60 + 0), which is again incorrect because this would mean there is a difference of 11 hours, when the difference is actually 13 hours.
What I have so far
I've realized that for example 1 and for example 2, the difference in minutes can be calculated with
(((24 + userHours) * 60) + userMinutes) - currTimeInMins
I'm struggling to come up with decision statements in the method to determine whether to use the first method or the second method to calculate the difference in minutes.
The Code
// Listener for the time selection
TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String currAM_PM = "";
String userAM_PM = "";
// Get user AM/PM
int hourToShow = 0;
if (hourOfDay > 12){
hourToShow = hourOfDay - 12;
userAM_PM = "PM"
}
else if (hourOfDay == 12){
hourToShow = hourOfDay;
userAM_PM = "PM"
}
else{
hourToShow = hourOfDay;
userAM_PM = "AM"
}
// Update the time field to show the selected time in 12-hr format
EditText timeField = (EditText) findViewById(R.id.editTime);
timeField.setText(hourToShow + ":" + minute + " " + userAM_PM);
// Get current hour
SimpleDateFormat sdf = new SimpleDateFormat("HH");
String cHour = sdf.format(new Date());
int currHour = Integer.parseInt(cHour);
// Get current AM/PM
if (currHour > 12){
currAM_PM = "PM"
}
else if (currHour == 12){
currAM_PM = "PM"
}
else{
currAM_PM = "AM"
}
// Calculate the time to use
// If the selected hour is less than the current hour AND am_pm is "AM"
// THIS IS THE WHERE I NEED HELP
//--------------------------------------------------------------
if(currAM_PM == "PM" && userAM_PM == "AM" .... ??????) {
//take 24, add the hour, use same minute. so that 3 am is 27:00.
timeToUse = ((24 + hourOfDay) * 60) + minute;
}
else
timeToUse = (hourOfDay * 60) + minute;
}
// timeToUse is then passed through an intent extra to the next activity
// where the difference between it and the current time is calculated and used
// for other purposes.
};
Thanks for any help ahead of time.
Solution
I used a DatePickerDialog and a TimePickerDialog to load a Calendar object with the user selected year, month, etc.
Then I created a Date object, initializing it to cal.getDate().
I then loaded Date.getDate() into a long variable, giving the time in miliseconds from Jan 1, 1970.
I then divided this number by 60000 to get the time in minutes.
I did the same thing for the current date, and found the difference in between the two.
Thanks for all help.

how to get diff b/w two dates without using api?

i tried to get the following way but my guide instruct me to do without using api..
can any one give it solution?
public class DateDifferenceExample{
public static void main(String[] args){
//get instance of Calendar objects
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
//set two dates we want to know difference of
cal1.set(2006, 12, 30);
cal2.set(2007, 5, 3);
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
//difference in milliseconds
long diff = milis2 - milis1;
//difference in seconds
long diffSeconds = diff / 1000;
//difference in minutes
long diffMinutes = diff / (60 * 1000);
//difference in hours
long diffHours = diff / (60 * 60 * 1000);
//difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Date difference in milliseconds: " + diff + " milliseconds.");
System.out.println("Date difference in seconds: " + diffSeconds + " seconds.");
System.out.println("Date difference in minutes: " + diffMinutes + " minutes.");
System.out.println("Date difference in hours: " + diffHours + " hours.");
System.out.println("Date difference in days: " + diffDays + " days.");
}
}
You can use the compareTo() method or the before() and after() methods to compare the dates. If you need the 'difference' then I recommend that you start comparing with years, then month and then days. That way you can get the exact difference between two dates.
i don't want to use any methods
You will need to use methods to get the year, month and day. Have a look at: Calendar.get()
Example:
Date1: 01 / 01 / 2014
Date2: 02 / 12 / 2015
Start with year. Subtract the years, use Math.abs() to get the absolute value.
Then go for month. Subtract the months, use Math.abs() to get the absolute value.
Then finally the day. Same story.
The two dates are 1 year, 11 month and 1 day apart
Note: The dates are in dd/mm/yyyy format
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.set(2006, 12, 30);
cal2.set(2007, 5, 3);
long startTime = cal1.getTimeInMillis();
long endTime = cal2.getTimeInMillis();
long diff = endTime - startTime;
long hoursRem=diff%(1000*60*60);
diff=diff-hoursRem;
long hours=diff/(1000*60*60);
diff=diff+hoursRem;
diff = diff - (hours * 60 * 60 * 1000);
long minRem=diff%(1000*60);
diff=diff-minRem;
long min=diff/(1000*60);
diff=diff+minRem;
diff = diff - (min * 60 * 1000);
long seconds=diff/1000;
System.out.println("hh = "+hours +" min ="+min+" sec= "+seconds);
The code is OK. But it may be not exact for days because it does not take daylight savings.
Consider this
GregorianCalendar c1 = new GregorianCalendar(2014, 2, 29, 4, 0, 0);
GregorianCalendar c2 = new GregorianCalendar(2014, 2, 30, 4, 0, 0);
the difference in days is 1 full day. But this
System.out.println(c2.getTimeInMillis() - c1.getTimeInMillis());
prints
82800000
that is difference in millis is 1 hour less, and your code for diffDays will produce 0

Difference between two dates?

Friends,
I am looking to calculate the difference in days.
Hey suppose if I enter 31st Aug 23:59:00 and next date 1 Sept 00:02:00 , I need to show the record as 1 day.
Please help me for this one.
Right now I am calculating the same using .getTimeInMillis() but it is not giving me expected results for the date condition mentioned above.
I you look for day and time difference then, use my code
public class AndroidWebImage extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Date sdate=Calendar.getInstance().getTime();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
String setDate = "13/09/12 10:20:43";
Date AlarmDate=new Date(setDate);
String currentDate = format.format(sdate);
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(setDate);
d2 = format.parse(currentDate);
} catch (ParseException e) {
e.printStackTrace();
}
//Comparison
long diff = d1.getTime() - d2.getTime();
long diffSeconds = diff / 1000 % 60;
long days = (int) (diff / (1000 * 60 * 60 * 24));
long diffHours = (int) ((diff- (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
long diffMinutes = (int) (diff- (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * diffHours))/ (1000 * 60);
int curhour=sdate.getHours();
int curmin=sdate.getMinutes();
int alarmhour=AlarmDate.getHours();
int alarmmin=AlarmDate.getMinutes();
if(curhour==alarmhour && curmin==alarmmin)
{
Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
}
else if(curhour>=alarmhour && curmin>=alarmmin || curhour<=alarmhour && curmin<=alarmmin)
{
Toast.makeText(getApplicationContext(), String.valueOf(days+"days\n"+diffHours+"hrs"+diffMinutes+"min\n"+diffSeconds+"sec"),Toast.LENGTH_LONG).show();
}
}
}
You can't do this with millis, because you need to know where the day boundary falls (i.e. midnight). A millisecond either side of midnight means two different days.
You need to use a Calendar to determine how many days lie within the interval between your two dates. The JodaTime library has a lot of additional support for this kind of calculation.
See also Calculating the difference between two Java date instances
Your're just trying to find the number of days, right?
Try looking at this, it might have what you are looking for.
i made this code before, its may helps you
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* #author MErsan
*/
public class DateFormatter {
public static String formatDate(long time) {
StringBuilder result = new StringBuilder();
// 1- Check the year
// 2- Check the Month
// 3- Check the Day
// 4- Check the Hours
Date myDate = new Date(time);
Date todayDate = new Date(System.currentTimeMillis());
if (todayDate.getYear() - myDate.getYear() != 0) {
// Not same year, and should append the whole time
return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
}
// Same Year
// now Check the month
if (todayDate.getMonth() - myDate.getMonth() != 0) {
return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
// 16,
// 11:55
// PM
}
// Now Same Month
// Check the day
int daysDiff = todayDate.getDate() - myDate.getDate();
if (daysDiff == 1) {// Yesterday
result.append("Yesterday").append(' ');
result.append(new SimpleDateFormat("hh:mm a").format(myDate));
return result.toString();
} else if (daysDiff != 0) {
return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
// 16,
// 11:55
// PM
}
// Same Day :')
// Check the hour
int hoursDiff = todayDate.getHours() - myDate.getHours();
if (hoursDiff < 0) {// Invalid Time
// :#
result.append("Today").append(' ');
result.append(new SimpleDateFormat("hh:mm a").format(myDate));
return result.toString();
} else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
result.append("Today").append(' ');
result.append(new SimpleDateFormat("hh:mm a").format(myDate));
return result.toString();
} else if (hoursDiff != 0) {// Hours Diff less than 3 hours, but not
// current hour
int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
result.append("Before").append(' ');
result.append(hoursDiff).append(' ');
result.append("Hours").append(' ');
result.append("and").append(' ');
result.append(Math.abs(mintuesDiff)).append(' ');
result.append("Minutes");
System.err.println("Case 6");
return result.toString();
} else if (hoursDiff == 0) {// Same Hours
int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
if (mintuesDiff < 1) {// Seconds Only {Same Minute}
int secondsDiff = todayDate.getSeconds() - myDate.getSeconds();
result.append("Before").append(' ');
result.append(Math.abs(secondsDiff)).append(' ');
result.append("Seconds");
return result.toString();
} else {
result.append("Before").append(' ');
result.append(Math.abs(mintuesDiff)).append(' ');
result.append("Minutes");
return result.toString();
}
}
// Default
return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
}
}
import java.util.Calendar;
public class DateDifference
{
public static void main(String[] args)
{
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(2012, 01, 10);
calendar2.set(2012, 07, 01);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Time in days: " + diffDays + " days.");
}
}
You need to get rid of the timestamps and then subtract dates to get the difference in dates or you can use Joda-time as below:
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;
Date past = new Date(112, 8, 1);
Date today = new Date(112, 7, 30);
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays();
Re-post:
There's a simple solution, that at least for me, is the only feasible solution.
The problem is that all the answers I see being tossed around - using Joda, or Calendar, or Date, or whatever - only take the amount of milliseconds into consideration. They end up counting the number of 24-hour cycles between two dates, rather than the actual number of days. So something from Jan 1st 11pm to Jan 2nd 1am will return 0 days.
To count the actual number of days between startDate and endDate, simply do:
// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;
// Find the difference, duh
long daysBetween = endDay - startDay;
This will return "1" between Jan 2nd and Jan 1st. If you need to count the end day, just add 1 to daysBetween (I needed to do that in my code since I wanted to count the total number of days in the range).

How to subtract n days from current date in java? [duplicate]

This question already has answers here:
How to subtract X days from a date using Java calendar?
(11 answers)
Closed 7 years ago.
I want to subtract n days from the current date in Java.
How do I do that?
You don't have to use Calendar. You can just play with timestamps :
Date d = initDate();//intialize your date to any date
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 l ); //Subtract n days
UPDATE
DO NOT FORGET TO ADD "l" for long by the end of 1000.
Please consider the below WARNING:
Adding 1000*60*60*24 milliseconds to a java date will once in a great while add zero days or two days to the original date in the circumstances of leap seconds, daylight savings time and the like. If you need to be 100% certain only one day is added, this solution is not the one to use.
this will subtract ten days of the current date (before Java 8):
int x = -10;
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, x);
Date tenDaysAgo = cal.getTime();
If you're using Java 8 you can make use of the new Date & Time API (http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html):
LocalDate tenDaysAgo = LocalDate.now().minusDays(10);
For converting the new to the old types and vice versa see: Converting between java.time.LocalDateTime and java.util.Date
I found this perfect solution and may useful, You can directly get in format as you want:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -90); // I just want date before 90 days. you can give that you want.
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); // you can specify your format here...
Log.d("DATE","Date before 90 Days: " + s.format(new Date(cal.getTimeInMillis())));
Thanks.
for future use find day of the week ,deduct day and display the deducted day using date.
public static void main(String args[]) throws ParseException {
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date dt1 = format1.parse("20/10/2013");
Calendar c = Calendar.getInstance();
c.setTime(dt1);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
long diff = Calendar.getInstance().getTime().getTime() ;
System.out.println(dayOfWeek);
switch (dayOfWeek) {
case 6:
System.out.println(days[dayOfWeek - 1]);
break;
case 5:
System.out.println(days[dayOfWeek - 1]);
break;
case 4:
System.out.println(days[dayOfWeek - 1]);
break;
case 3:
System.out.println(days[dayOfWeek - 1]);
break;
case 2:
System.out.println(days[dayOfWeek - 1]);
break;
case 1:
System.out.println(days[dayOfWeek - 1]);
diff = diff -(dt1.getTime()- 3 );
long valuebefore = dt1.getTime();
long valueafetr = dt1.getTime()-2;
System.out.println("DATE IS befor subtraction :"+valuebefore);
System.out.println("DATE IS after subtraction :"+valueafetr);
long x= dt1.getTime()-(2 * 24 * 3600 * 1000);
System.out.println("Deducted date to find firday is - 2 days form Sunday :"+new Date((dt1.getTime()-(2*24*3600*1000))));
System.out.println("DIffrence from now on is :"+diff);
if(diff > 0) {
diff = diff / (1000 * 60 * 60 * 24);
System.out.println("Diff"+diff);
System.out.println("Date is Expired!"+(dt1.getTime() -(long)2));
}
break;
}
}
As #Houcem Berrayana say
If you would like to use n>24 then you can use the code like:
Date dateBefore = new Date((d.getTime() - n * 24 * 3600 * 1000) - n * 24 * 3600 * 1000);
Suppose you want to find last 30 days date, then you'd use:
Date dateBefore = new Date((d.getTime() - 24 * 24 * 3600 * 1000) - 6 * 24 * 3600 * 1000);

(Java / Android) Calculate days between 2 dates and present the result in a specific format

I am trying to do calculate days between 2 dates as follow:
Obtain current date
Obtain past OR future date
Calculate the difference between no. 1 and no. 2
Present the dates in the following format
If the result is in past (2 day ago) or in the future (in 2 days)
Format will: days, weeks, months, years
I tried different ways but couldn't get the result I wanted above. I found out that Android DatePicker dialog box convert date into Integer. I have not found a way to make DatePicket widget to return date variables instead of integer.
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, **int** year,
**int** monthOfYear, **int** dayOfMonth) {
enteredYear = year;
enteredMonth = monthOfYear;
enteredDay = dayOfMonth;
}
};
I tried to convert the system date to Integer, based on the above, but this doesn't really work when trying to calculate days between 2 dates.
private void getSystemDate(){
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
systemYear = mYear;
mMonth = c.get(Calendar.MONTH);
systemMonth = mMonth + 1;
mDay = c.get(Calendar.DAY_OF_MONTH);
systemDay = mDay;
}
/**
* Returns a string that describes the number of days
* between dateOne and dateTwo.
*
*/
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "dateTwo is " + delta + " days after dateOne";
}
else {
delta *= -1;
return "dateTwo is " + delta + " days before dateOne";
}
}
Edit: Just saw the same question in another thread:
how to calculate difference between two dates using java
Edit2: To get Year/Month/Week, do something like this:
int year = delta / 365;
int rest = delta % 365;
int month = rest / 30;
rest = rest % 30;
int weeks = rest / 7;
int days = rest % 7;
long delta = Date2.getTime() - Date1.getTime();
new Date(delta);
From here, you just pick your format. Maybe use a date formatter? As for determing the future stuff and all that, you could just see if the delta is positive or negative. A negative delta will indicate a past event.
Well, java/android API has all answers for you:
Calendar myBirthday=Calendar.getInstance();
myBirthday.set(1980, Calendar.MARCH, 22);
Calendar now = Calendar.getInstance();
long diffMillis= Math.abs(now.getTimeInMillis()-myBirthday.getTimeInMillis());
long differenceInDays = TimeUnit.DAYS.convert(diffMillis, TimeUnit.MILLISECONDS);

Categories

Resources