Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrement a date in Java

I want to get the previous day (24 hours) from the current time.

e.g if current time is Date currentTime = new Date();

2011-04-25 12:15:31:562 GMT

How to determine time i.e

2011-04-24 12:15:31:562 GMT

like image 895
Muhammad Imran Tariq Avatar asked Apr 27 '11 05:04

Muhammad Imran Tariq


People also ask

How do you decrement a date?

DateTime yesterday = new DateTime(). minusDays(1);

How do you subtract date in Java?

The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31. This instance is immutable and unaffected by this method call.

How can I increment a date by one day in Java?

Date today = new Date(); SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd"); Calendar c = Calendar. getInstance(); c. add(Calendar. DATE, 1); // number of days to add String tomorrow = (String)(formattedDate.

Is Date deprecated in Java?

Description. Some java. util. Date constructors like new Date(int year, int month, int day) , new Date(int year, int month, int date, int hrs, int min) and new Date(int year, int month, int date, int hrs, int min, int sec) are deprecated and the Calendar should be used instead.


2 Answers

You can do that using Calendar class:

Calendar cal = Calendar.getInstance();
cal.setTime ( date ); // convert your date to Calendar object
int daysToDecrement = -1;
cal.add(Calendar.DATE, daysToDecrement);
date = cal.getTime(); // again get back your date object
like image 118
anubhava Avatar answered Oct 08 '22 20:10

anubhava


please checkout this here: Java Date vs Calendar

Calendar cal=Calendar.getInstance();
cal.setTime(date); //not sure if date.getTime() is needed here
cal.add(Calendar.DAY_OF_MONTH, -1);
Date newDate = cal.getTime();
like image 44
nils petersohn Avatar answered Oct 08 '22 20:10

nils petersohn