Decrement a date in Java - 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

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

I would suggest you use Joda Time to start with, which is a much nicer API. Then you can use:
DateTime yesterday = new DateTime().minusDays(1);
Note that "this time yesterday" isn't always 24 hours ago though... you need to think about time zones etc. You may want to use LocalDateTime or Instant instead of DateTime.

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

24 hours and 1 day are not the same thing. But you do both using Calendar:
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, -1);
Date d = c.getTime();
If you are going back 24 hours, you would use Calendar.HOUR_OF_DAY

java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println("Now: " + now);
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println("Yesterday: " + yesterday);
}
}
Output of a sample run:
Now: 2021-07-16T20:40:24.402592Z
Yesterday: 2021-07-15T20:40:24.402592Z
ONLINE DEMO
For any reason, if you need to convert this object of Instant to an object of java.util.Date, you can do so as follows:
Date date = Date.from(odt.toInstant());
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Related

How to get day of week name from selected date month and year in Android?

I tried the below code but it gives me the name of the day of week two days ago.
DatePicker picker;
int date = picker.DayOfMonth;
int month = (picker.Month + 1);//month is 0 based
int year = picker.Year;
SimpleDateFormat simpledateformat = new SimpleDateFormat("EEE");
Date dt = new Date(year, month, date);
First convert your Date in to specific Date format using SimpleDateFormat
Use SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE"); to get Day name in week
WHERE EEEE -> Day name in week
SAMPLE CODE
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date myDate = inFormat.parse(date+"-"+month+"-"+year);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
String dayName=simpleDateFormat.format(myDate);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE", Locale.US);
String asWeek = dateFormat.format(dt);
DateTimeFormatter dayOfWeekFormatter
= DateTimeFormatter.ofPattern("EEE", Locale.ENGLISH);
LocalDate date = LocalDate.of(
picker.getYear(), picker.getMonth(), picker.getDayOfMonth());
System.out.println(date.format(dayOfWeekFormatter));
Picking 2018-04-09 this printed
Mon
I am using and recommending java.time, the modern Java date and time API. The Date class is long outdated, and you are using a deprecated constructor. It was deprecated because it works unreliably across time zones, so you shouldn’t. SimpleDateFormat is not only outdated, it is also notoriously troublesome. I recommend you avoid those classes altogether. The modern API is so much nicer to work with.
What went wrong in your code?
You’ve got two bugs apart from using the deprecated Date constructor and the outdated classes:
It’s the Date’s month that is 0-based (not that of DatePicker), so you need to subtract 1, not add 1 (or maybe they are both 0-based??).
The deprecated Date constructor’s year is “1900-based”. This may have seemed a good idea when the class was designed in the 1990’s: you could just specify 95 to get 1995. When you pass 2018 to the constructor, you get year 3918. That’s right. :-(
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Calendar calendar = Calendar.getInstance();
DateFormat date4= new SimpleDateFormat("EEEE", Locale.getDefault());
String localTime4 = date4.format(calendar.getTime());
Simple and easy way
just use this

Facing issue with Calendar object

I have a task in which i need to set hour, minute, meridian programmatically to Calendar object and need to display time in a format hh:mm a. Here below is my code so far.
Calendar calendar = (Calendar)dateNtime.clone();
calendar.set(Calendar.HOUR, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.AM_PM, 1);
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a");
String str = dateFormat.format(calendar.getTimeInMillis());
Where dateNTime is an existing calendar object which i have to use in constructing new one.
All is going fine except only a case while i set 12PM. it always format hh:mm a and results 12:00AM while it should be 12:00PM.
please help if anybody have a good experience with Calendar object and it's known issue or provide me if there is a good tutorial link.
The HOUR field is documented as:
Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11).
So instead of setting it to 12, you should set it to 0.
Personally I'd just set the HOUR_OF_DAY field, adding 12 hours if you want to make it PM - and don't set the AM_PM field at all.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern API:
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Replace JVM's default timezone, ZoneId.systemDefault() with the applicable
// timezone e.g. ZoneId.of("America/New_York")
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.systemDefault())
.withHour(12)
.withMinute(0);
System.out.println(zdt);
// Get and display just time in default format
LocalTime time = zdt.toLocalTime();
System.out.println(time);
// Display just time in a custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
// Alternatively, dtf.format(time);
String formatted = dtf.format(zdt);
System.out.println(formatted);
}
}
Output:
2021-06-06T12:00:15.855986+01:00[Europe/London]
12:00:15.855986
12:00 PM
ONLINE DEMO
How to convert Calendar to java.time type?
Instant instant = calendar.toInstant();
// Replace JVM's default timezone, ZoneId.systemDefault() with the applicable
// timezone e.g. ZoneId.of("America/New_York")
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
What if I need Calendar object from java.time type?
For any reason, if you need to convert this object of ZonedDateTime to an object of java.util.Calendar, you can do so as follows:
Calendar calendar = Calendar.getInstance();
calendar.setTime(Date.from(zdt.toInstant()));
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
Sometimes, comments get deleted and therefore quoting below a valuable comment from Ole V.V.:
For a more accurate conversion to Calendar you may use
GregorianCalendar.from(zdt)
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

java get last day in next month

I have variable nowDate type of Date and I want set variable nextDate contains last day in next month.
For example:
nowDate = 2013-04-16
So nextDate will contains 2013-05-31
How can I do that?
Try
private static Date getNextDate(Date nowDate) {
Calendar c = Calendar.getInstance();
c.setTime(nowDate);
c.add(Calendar.MONTH, 1);
c.set(Calendar.DATE, c.getMaximum(Calendar.DATE));
Date nextDate = c.getTime();
return nextDate;
}
Usage:
Date nowDate = new Date();
Date nextDate = getNextDate(nowDate);
Similar to Xavi but one less line of code :-)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
You could try setting a Calendar to day one two months ahead, and then substract one day:
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 2);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DATE, -1);
Date nextDate = c.getTime();
As others have already pointed out, you could also just add one month, and use Calendar.getActualMaximum() to set the last day of the following month.
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 1);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextDate = c.getTime();
tl;dr
Very easy.
YearMonth.now() // Get entire month for the date current in the JVM’s current default time zone. Better to pass explicitly your desired/expected time zone.
.plusMonths( 1 ) // Move to the following month.
.atEndOfMonth() // Returns a `LocalDate` object, for a date-only value without time-of-day and without time zone.
.toString() // Generate a String in standard ISO 8601 format.
2018-02-28
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes.
Get the date.
LocalDate today = LocalDate.now();
Better to pass explicitly the desired/expected time zone.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
Pull the YearMonth from that, to represent the month as a whole.
YearMonth ym = YearMonth.from( today ) ;
Or skip the LocalDate entirely.
YearMonth ym = YearMonth.now( ZoneId.of( "America/Montreal" ) ) ;
Move to next month.
YearMonth ymNext = ym.plusMonths( 1 ) ;
Get the date at end of the month.
LocalDate ld = ymNext.atEndOfMonth() ;
Generate a String in standard ISO 8601 format: YYYY-MM-DD.
String output = ld.toString() ;
For other formats, search Stack Overflow for DateTimeFormatter class.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Using joda and cribbing off sinarf:
DateTime dt = new DateTime().plusMonths(1);
DateTime lastJoda = dt.dayOfMonth().withMaximumValue();
Date last = lastJoda.toDate();
System.out.println(last.toString());
One way is to increment 2 months to your current month and set the date as 1st. After that decrement the date by 1 and it will give you the last day of month. This will automatically take care of leap year, 30 days, 31 days, 29 days and 28 days months. Program below
public class LastDayofNextMonth {
public static void main(String args[])
{
Calendar cal = Calendar.getInstance();
cal.set(2013,Calendar.APRIL, 14) ;
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+2);
cal.set(Calendar.DATE,1);
cal.add(Calendar.DATE,-1);
System.out.println(cal.getTime().toString());
}
}
Use Calendar:
First Set the Calendar to the next month.
Use: cal.add(Calendar.MONTH, 1);
Then Use getActualMaximum to calculate the last day of the month that you set in previous step.
import java.util.Calendar;
import java.util.Date;
public class Main{
public static void main(String ar[]){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
cal.add(Calendar.MONTH, 1);
Date lastDateOfNextMonth = cal.getTime();
System.out.println(lastDateOfNextMonth );
}
}
IDEONE DEMO
we have so many good answers, however all above answers have code like:
cal.add(Calendar.MONTH, 1);
this code produce a little confusion because Months start at 0, so 1 is for February.
(Edit: The integer in the add() function is not the month number (1=february) but the number of months to add )
You can do the following to get last day of month
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

How do I get a Date without time in Java?

Continuing from Stack Overflow question Java program to get the current date without timestamp:
What is the most efficient way to get a Date object without the time? Is there any other way than these two?
// Method 1
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dateWithoutTime = sdf.parse(sdf.format(new Date()));
// Method 2
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
dateWithoutTime = cal.getTime();
Update:
I knew about Joda-Time; I am just trying to avoid additional library for such a simple (I think) task. But based on the answers so far Joda-Time seems extremely popular, so I might consider it.
By efficient, I mean I want to avoid temporary object String creation as used by method 1, meanwhile method 2 seems like a hack instead of a solution.
Do you absolutely have to use java.util.Date? I would thoroughly recommend that you use Joda Time or the java.time package from Java 8 instead. In particular, while Date and Calendar always represent a particular instant in time, with no such concept as "just a date", Joda Time does have a type representing this (LocalDate). Your code will be much clearer if you're able to use types which represent what you're actually trying to do.
There are many, many other reasons to use Joda Time or java.time instead of the built-in java.util types - they're generally far better APIs. You can always convert to/from a java.util.Date at the boundaries of your own code if you need to, e.g. for database interaction.
Here is what I used to get today's date with time set to 00:00:00:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date today = new Date();
Date todayWithZeroTime = formatter.parse(formatter.format(today));
You can use the DateUtils.truncate from Apache Commons library.
Example:
DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH)
tl;dr
Is there any other way than these two?
Yes, there is: LocalDate.now
LocalDate.now(
ZoneId.of( "Pacific/Auckland" )
)
java.time
Java 8 and later comes with the new java.time package built-in. See Tutorial. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Similar to Joda-Time, java.time offers a LocalDate class to represent a date-only value without time-of-day and without time zone.
Note that time zone is critical to determining a particular date. At the stroke of midnight in Paris, for example, the date is still “yesterday” in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
By default, java.time uses the ISO 8601 standard in generating a string representation of a date or date-time value. (Another similarity with Joda-Time.) So simply call toString() to generate text like 2015-05-21.
String output = today.toString() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The most straightforward way:
long millisInDay = 60 * 60 * 24 * 1000;
long currentTime = new Date().getTime();
long dateOnly = (currentTime / millisInDay) * millisInDay;
Date clearDate = new Date(dateOnly);
The standard answer to these questions is to use Joda Time. The API is better and if you're using the formatters and parsers you can avoid the non-intuitive lack of thread safety of SimpleDateFormat.
Using Joda means you can simply do:
LocalDate d = new LocalDate();
Update:: Using java 8 this can be acheived using
LocalDate date = LocalDate.now();
This is a simple way of doing it:
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateOnly = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(dateOnly.format(cal.getTime()));
It does not make sense to talk about a date without a timestamp with regards to the Date routines in the standard java runtime, as it essentially maps down to a specific millisecond and not a date. Said millisecond intrinsically has a time of day attached to it which makes it vulnerable to timezone problems like Daylight Savings Time and other calendar adjustments. See Why is subtracting these two times (in 1927) giving a strange result? for an interesting example.
If you want to work with dates instead of milliseconds, you need to use something else. For Java 8 there is a new set of methods providing exactly what you ask for. For Java 7 and earlier use http://www.joda.org/joda-time/
// 09/28/2015
System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));
// Mon Sep 28
System.out.println( new Date().toString().substring(0, 10) );
// 2015-09-28
System.out.println(new java.sql.Date(System.currentTimeMillis()));
// 2015-09-28
// java 8
System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class
Definitely not the most correct way, but if you just need a quick solution to get the date without the time and you do not wish to use a third party library this should do
Date db = db.substring(0, 10) + db.substring(23,28);
I only needed the date for visual purposes and couldn't Joda so I substringed.
If all you want is to see the date like so "YYYY-MM-DD" without all the other clutter e.g. "Thu May 21 12:08:18 EDT 2015" then just use java.sql.Date. This example gets the current date:
new java.sql.Date(System.currentTimeMillis());
Also java.sql.Date is a subclass of java.util.Date.
Well, as far as I know there is no easier way to achieve this if you only use the standard JDK.
You can, of course, put that logic in method2 into a static function in a helper class, like done here in the toBeginningOfTheDay-method
Then you can shorten the second method to:
Calendar cal = Calendar.getInstance();
Calendars.toBeginningOfTheDay(cal);
dateWithoutTime = cal.getTime();
Or, if you really need the current day in this format so often, then you can just wrap it up in another static helper method, thereby making it a one-liner.
Use LocalDate.now() and convert into Date like below:
Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
What about this?
public static Date formatStrictDate(int year, int month, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
If you need the date part just for echoing purpose, then
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
If you just need the current date, without time, another option is:
DateTime.now().withTimeAtStartOfDay()
Yo can use joda time.
private Date dateWitoutTime(Date date){
return new LocalDate(date).toDate()
}
and you call with:
Date date = new Date();
System.out.println("Without Time = " + dateWitoutTime(date) + "/n With time = " + date);
Check out Veyder-time. It is a simple and efficient alternative to both java.util and Joda-time. It has an intuitive API and classes that represent dates alone, without timestamps.
The most straigthforward way that makes full use of the huge TimeZone Database of Java and is correct:
long currentTime = new Date().getTime();
long dateOnly = currentTime + TimeZone.getDefault().getOffset(currentTime);
Here is a clean solution with no conversion to string and back, and also it doesn't re-calculate time several times as you reset each component of the time to zero. It also uses % (modulus) rather than divide followed by multiply to avoid the double operation.
It requires no third-party dependencies, and it RESPECTS THE TIMEZONE OF THE Calender object passed in. This function returns the moment in time at 12 AM in the timezone of the date (Calendar) you pass in.
public static Calendar date_only(Calendar datetime) {
final long LENGTH_OF_DAY = 24*60*60*1000;
long millis = datetime.getTimeInMillis();
long offset = datetime.getTimeZone().getOffset(millis);
millis = millis - ((millis + offset) % LENGTH_OF_DAY);
datetime.setTimeInMillis(millis);
return datetime;
}
Prefer not to use third-party libraries as much as possible. I know that this way is mentioned before, but here is a nice clean way:
/*
Return values:
-1: Date1 < Date2
0: Date1 == Date2
1: Date1 > Date2
-2: Error
*/
public int compareDates(Date date1, Date date2)
{
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
try
{
date1 = sdf.parse(sdf.format(date1));
date2 = sdf.parse(sdf.format(date2));
}
catch (ParseException e) {
e.printStackTrace();
return -2;
}
Calendar cal1 = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
cal1.setTime(date1);
cal2.setTime(date2);
if(cal1.equals(cal2))
{
return 0;
}
else if(cal1.after(cal2))
{
return 1;
}
else if(cal1.before(cal2))
{
return -1;
}
return -2;
}
Well, not using GregorianCalendar is maybe an option!
I just made this for my app :
public static Date getDatePart(Date dateTime) {
TimeZone tz = TimeZone.getDefault();
long rawOffset=tz.getRawOffset();
long dst=(tz.inDaylightTime(dateTime)?tz.getDSTSavings():0);
long dt=dateTime.getTime()+rawOffset+dst; // add offseet and dst to dateTime
long modDt=dt % (60*60*24*1000) ;
return new Date( dt
- modDt // substract the rest of the division by a day in milliseconds
- rawOffset // substract the time offset (Paris = GMT +1h for example)
- dst // If dayLight, substract hours (Paris = +1h in dayLight)
);
}
Android API level 1, no external library.
It respects daylight and default timeZone. No String manipulation so I think this way is more CPU efficient than yours but I haven't made any tests.
We can use SimpleDateFormat to format the date as we like. here is a working example below:-
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(new Date())); //data can be inserted in this format function
Output:
15/06/2021

How to subtract X days from a date using Java calendar?

Anyone know a simple way using Java calendar to subtract X days from a date?
I have not been able to find any function which allows me to directly subtract X days from a date in Java. Can someone point me to the right direction?
Taken from the docs here:
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:
Calendar calendar = Calendar.getInstance(); // this would default to now
calendar.add(Calendar.DAY_OF_MONTH, -5).
You could use the add method and pass it a negative number. However, you could also write a simpler method that doesn't use the Calendar class such as the following
public static void addDays(Date d, int days)
{
d.setTime( d.getTime() + (long)days*1000*60*60*24 );
}
This gets the timestamp value of the date (milliseconds since the epoch) and adds the proper number of milliseconds. You could pass a negative integer for the days parameter to do subtraction. This would be simpler than the "proper" calendar solution:
public static void addDays(Date d, int days)
{
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, days);
d.setTime( c.getTime().getTime() );
}
Note that both of these solutions change the Date object passed as a parameter rather than returning a completely new Date. Either function could be easily changed to do it the other way if desired.
Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.
FYI in Joda Time you could do
DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);
tl;dr
LocalDate.now().minusDays( 10 )
Better to specify time zone.
LocalDate.now( ZoneId.of( "America/Montreal" ) ).minusDays( 10 )
Details
The old date-time classes bundled with early versions of Java, such as java.util.Date/.Calendar, have proven to be troublesome, confusing, and flawed. Avoid them.
java.time
Java 8 and later supplants those old classes with the new java.time framework. See Tutorial. Defined by JSR 310, inspired by Joda-Time, and extended by theThreeTen-Extra project. The ThreeTen-Backport project back-ports the classes to Java 6 & 7; the ThreeTenABP project to Android.
The Question is vague, not clear if it asks for a date-only or a date-time.
LocalDate
For a date-only, without time-of-day, use the LocalDate class. Note that a time zone in crucial in determining a date such as "today".
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
LocalDate tenDaysAgo = today.minusDays( 10 );
ZonedDateTime
If you meant a date-time, then use the Instant class to get a moment on the timeline in UTC. From there, adjust to a time zone to get a ZonedDateTime object.
Instant now = Instant.now(); // UTC.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
ZonedDateTime tenDaysAgo = zdt.minusDays( 10 );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
int x = -1;
Calendar cal = ...;
cal.add(Calendar.DATE, x);
See java.util.Calendar#add(int,int)
Instead of writing my own addDays as suggested by Eli, I would prefer to use DateUtils from Apache. It is handy especially when you have to use it multiple places in your project.
The API says:
addDays(Date date, int amount)
Adds a number of days to a date returning a new object.
Note that it returns a new Date object and does not make changes to the previous one itself.
I faced the same challenge where I needed to go back by 1 day (should be able to roll back by one even if previous day falls into previous year or months).
I did following, basically subtracted by 24 hours for 1 day.
someDateInGregorianCalendar.add(Calendar.HOUR, -24);
Alternatively, I could also do
GregorianCalendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR, 2021);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DATE, 1);
System.out.println("Original: " + cal.getTime());
cal.add(Calendar.DATE, -1);
System.out.println("After adding DATE: " + cal.getTime());
OUTPUT:
Original: Fri Jan 01 15:08:33 CET 2021
After adding DATE: Thu Dec 31 15:08:33 CET 2020
It can be done easily by the following
Calendar calendar = Calendar.getInstance();
// from current time
long curTimeInMills = new Date().getTime();
long timeInMills = curTimeInMills - 5 * (24*60*60*1000); // `enter code here`subtract like 5 days
calendar.setTimeInMillis(timeInMills);
System.out.println(calendar.getTime());
// from specific time like (08 05 2015)
calendar.set(Calendar.DAY_OF_MONTH, 8);
calendar.set(Calendar.MONTH, (5-1));
calendar.set(Calendar.YEAR, 2015);
timeInMills = calendar.getTimeInMillis() - 5 * (24*60*60*1000);
calendar.setTimeInMillis(timeInMills);
System.out.println(calendar.getTime());
I believe a clean and nice way to perform subtraction or addition of any time unit (months, days, hours, minutes, seconds, ...) can be achieved using the java.time.Instant class.
Example for subtracting 5 days from the current time and getting the result as Date:
new Date(Instant.now().minus(5, ChronoUnit.DAYS).toEpochMilli());
Another example for subtracting 1 hour and adding 15 minutes:
Date.from(Instant.now().minus(Duration.ofHours(1)).plus(Duration.ofMinutes(15)));
If you need more accuracy, Instance measures up to nanoseconds. Methods manipulating nanosecond part:
minusNano()
plusNano()
getNano()
Also, keep in mind, that Date is not as accurate as Instant. My advice is to stay within the Instant class, when possible.
Someone recommended Joda Time so - I have been using this CalendarDate class http://calendardate.sourceforge.net
It's a somewhat competing project to Joda Time, but much more basic at only 2 classes. It's very handy and worked great for what I needed since I didn't want to use a package bigger than my project. Unlike the Java counterparts, its smallest unit is the day so it is really a date (not having it down to milliseconds or something). Once you create the date, all you do to subtract is something like myDay.addDays(-5) to go back 5 days. You can use it to find the day of the week and things like that.
Another example:
CalendarDate someDay = new CalendarDate(2011, 10, 27);
CalendarDate someLaterDay = today.addDays(77);
And:
//print 4 previous days of the week and today
String dayLabel = "";
CalendarDate today = new CalendarDate(TimeZone.getDefault());
CalendarDateFormat cdf = new CalendarDateFormat("EEE");//day of the week like "Mon"
CalendarDate currDay = today.addDays(-4);
while(!currDay.isAfter(today)) {
dayLabel = cdf.format(currDay);
if (currDay.equals(today))
dayLabel = "Today";//print "Today" instead of the weekday name
System.out.println(dayLabel);
currDay = currDay.addDays(1);//go to next day
}
Eli Courtwright second solution is wrong, it should be:
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -days);
date.setTime(c.getTime().getTime());

Categories

Resources