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

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

Related

Convert timestamp into specific format (year,month,week,days,time,hour,minute and second) in java [duplicate]

This question already has answers here:
How can I calculate a time span in Java and format the output?
(18 answers)
Closed 9 years ago.
This is my code,
e.g. 2year, 2 month, 1 week 2 days, 1 hour, 2 minutes , 35 seconds.
String stdate ="01/01/2014 09:30:30";
String endate ="09/11/2015 11:30:30";
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date d1 = new Date();
Date d2 = new Date();
long year =(1000*60*60*24*365l);
long month =(1000*60*60*24*30l);
long weeks =(1000*60*60*24*7l);
long days =(1000*60*60*24l);
try{
d1 = df.parse(stdate);
d2 = df.parse(endate);
long diff = d2.getTime()-d1.getTime();
long diffYear = diff/(1000*60*60*24*365l);
long diffMonth = (diff-(diffYear*year))/month;
long diffWeeks = ((diff%month))/weeks;
long diffDays = ((diff%weeks))/days;
System.out.println(diffYear+" years ");
System.out.println(diffMonth+" months ");
System.out.println(diffWeeks+" week ");
System.out.println(diffDays+" days "); // wrong output,
}catch(Exception e){
}
o/p:
1 years
10 months
2 week
5 days
I do not want to use joda time. it should be in java.util.*;
Please answer, thanks in advance.
You can try using Period from Joda-time
String stdate = "01/01/2014 09:30:30";
String endate = "09/11/2015 11:30:30";
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date d1 = df.parse(stdate);
Date d2 = df.parse(endate);;
DateTime startTime = new DateTime(d1), endTime = new DateTime(d2);
Period p = new Period(startTime, endTime);
System.out.printf("%-8s %d %n","years:",p.getYears());
System.out.printf("%-8s %d %n","months:",p.getMonths());
System.out.printf("%-8s %d %n","weeks:",p.getWeeks());
System.out.printf("%-8s %d %n","days:",p.getDays());
System.out.printf("%-8s %d %n","hours:",p.getHours());
System.out.printf("%-8s %d %n","minutes:",p.getMinutes());
System.out.printf("%-8s %d %n","second:",p.getSeconds());
Output:
years: 1
months: 10
weeks: 1
days: 1
hours: 2
minutes: 0
second: 0
Update:
To answer your original question: Just like you are subtracting days that already belongs to year from diff to calculate months, you need to subtract
sum of days used on year and month to calculate weeks
sum of days which already belong to year, month, week if you want to calculate days
so your code can look like
long diffYear = diff / year;
long diffMonth = (diff - (diffYear * year)) / month;
//long diffWeeks= ((diff % month)) / weeks;
long diffWeeks = (diff - (diffYear * year + diffMonth * month)) / weeks;
//long diffDays = ((diff % weeks)) / days;
long diffDays = (diff - (diffYear * year + diffMonth * month + diffWeeks*weeks)) / days;//((diff % weeks)) / days;
WARNING: This way of calculating days or weeks will treat each month as 30 days, which is not always true, because there can be also 28,29,30,31 day months. That is why instead of 1 day you will see 5.
WARNING 2: Instead of 1000*60*60*24*365l which for larger numbers can cause integer overflow (first numbers used are integers) you should use 1000L*60*60*24*365. So
change l to L because l looks like 1 so it can be confusing,
start multiplying with long.
To make things easier you can even write it as
long seconds = 1000L;
long minutes = seconds * 60;
long hours = minutes * 60;
long days = hours * 24;
long weeks = days * 7;
long month = days * 30;
long year = days * 365;

how to calculate number of days between two dates excluding weekend java [duplicate]

This question already has answers here:
Calculate number of weekdays between two dates in Java
(21 answers)
Calculating dates given two dates excluding weekend
(7 answers)
Closed 9 years ago.
Hi, i try this code to have days of works (including weekends) , so how can i exlude weekends between two dates ?
public long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
return diffDays;
}
This will work for you
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = df.parse("10/08/2013");
Date date2 = df.parse("21/08/2013");
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int numberOfDays = 0;
while (cal1.before(cal2)) {
if ((Calendar.SATURDAY != cal1.get(Calendar.DAY_OF_WEEK))
&&(Calendar.SUNDAY != cal1.get(Calendar.DAY_OF_WEEK))) {
numberOfDays++;
}
cal1.add(Calendar.DATE,1);
}
System.out.println(numberOfDays);
Live Demo
Out put
7

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

Calendar class: set to ten days from now

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;

(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