How to extract Day, Month and Year values from a string [like 18/08/2012]. I tried using SimpleDateFormat, but it returns a Date object and I observed that all the Get methods are deprecated. Is there any better way to do this?
Thanks
Personally I'd use Joda Time, which makes life considerably simpler. In particular, it means you don't need to worry about the time zone of the Calendar vs the time zone of a SimpleDateFormat - you can just parse to a LocalDate, which is what the data really shows you. It also means you don't need to worry about months being 0-based :)
Joda Time makes many date/time operations much more pleasant.
import java.util.*;
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) throws Exception {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy")
.withLocale(Locale.UK);
LocalDate date = formatter.parseLocalDate("18/08/2012");
System.out.println(date.getYear()); // 2012
System.out.println(date.getMonthOfYear()); // 8
System.out.println(date.getDayOfMonth()); // 18
}
}
Simply go for String.split(),
String str[] = "18/08/2012".split("/");
int day = Integer.parseInt(str[0]);
int month = Integer.parseInt(str[1]);
..... and so on
This should get you going without adding external jars
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date parse = sdf.parse("18/08/2012");
Calendar c = Calendar.getInstance();
c.setTime(parse);
System.out.println(c.get(Calendar.MONTH) + c.get(Calendar.DATE) + c.get(Calendar.YEAR));
Create a java.util.Calendar object out of that date as follows and extract the date parts:
Calendar cal = Calendar.getInstance();
cal.setTime(<date from simple-date-format).
cal.get(Calendar.MONTH);
etc.,
tl;dr
java.time.LocalDate.parse(
"18/08/2012" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
).getDayOfMonth() // .getYear() .getMonth()
java.time
The modern approach uses the java.time classes. Avoid the troublesome legacy classes such as Date & Calendar.
LocalDate
String input = "18/08/2012" ;
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
ld.toString(): 2012-08-18
Getter methods
Interrogate for the parts.
int d = ld.getDayOfMonth() ;
int m = ld.getMonthValue() ;
int y = ld.getYear() ;
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.
Another approach may be use Calendar object get(Calendar.MONT)
Example:
Calendar cal = Calendar.getInstance();
cal.setTime(dateObj).
cal.get(Calendar.MONTH);
(or)
You may use String.split() also.
Use This And Pass the date Value
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
Date parse = sdf.parse("18/01/2018");
Calendar calendar = Calendar.getInstance();
calendar.setTime(parse);
int date = calendar.get(Calendar.DATE);
//+1 Is Important Because if the month is January then coming 0 so Add +1
int month = calendar.get(Calendar.MONTH)+1;
int year = calendar.get(Calendar.YEAR);
System.out.println("Date:"+date +":Month:"+ month + ":Year:"+year);
In it the String is stored in an array in form of elements, and with the help of split() function, I have separated it and retrieved it from the array str[] and stored in 3 different variables day, month & year.
import java.util.*;
public class date {
public static void main(String[] args) throws Exception {
String str[] = "18/08/2012".split("/");
int day = Integer.parseInt(str[0]);
int month = Integer.parseInt(str[1]);
int year = Integer.parseInt(str[2]);
System.out.println(day);
System.out.println(month);
System.out.println(year);
}
}
Related
I am having quarter end date of last quarter let it be 30-09-20 , the requirement is to find end date of next quarter i.e 31-12-20. I am using below code to do the same but is it giving wrong output in some scenarios. This solution should be correct for all quarters.
String str = "30-09-20";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");
Date date = format.parse(str);
Date newDate = DateUtils.addMonths(date, 3);
System.out.println(newDate);//Dec 30 - It should be 31 Dec
To answer your question, I think you are looking for this :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
LocalDate end = LocalDate.parse("30-09-20", formatter)
.plusMonths(3) // add three months to your date
.with(TemporalAdjusters.lastDayOfMonth()); // with the last day of the month
Note: don't use the legacy Date library, you tagged your question Java-8 which mean you can use java-time API.
Get last day of current quarter
#deHaar have reason, to get the end date of curent quarter, I would suggest to use :
public LocalDate lastDayFromDateQuarter(String date) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
LocalDate ld = LocalDate.parse(date, formatter);
int quarter = ld.get(IsoFields.QUARTER_OF_YEAR); // Get the Quarter, 1, 2, 3, 4
// Then create a new date with new quarter * 3 and last day of month
return ld.withMonth(quarter * 3).with(TemporalAdjusters.lastDayOfMonth());
}
Get last day of next quarter
To get the last day of the next quarter, then you just can add three months to your date like so :
public static LocalDate lastDayFromDateQuarter(String date) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy");
LocalDate ld = LocalDate.parse(date, formatter);
int quarter = ld.get(IsoFields.QUARTER_OF_YEAR);
return ld.withMonth(quarter * 3)
.plusMonths(3)
.with(TemporalAdjusters.lastDayOfMonth());
}
tl;dr
Use YearQuarter class from ThreeTen-Extra.
YearQuarter // A class available in the ThreeTen-Extra library.
.from( // Factory method rather than calling `new`.
LocalDate.of( 2020 , Month.SEPTEMBER , 30 ) // Returns a `LocalDate` object, represent a date-only value without a time-of-day and without a time zone.
) // Returns a `YearQuarter` object.
.plusQuarters( 1 ) // Perform date-math, resulting in a new `YearQuarter` object (per immutable objects pattern).
.atEndOfQuarter() // Determine the date of last day of this year-quarter.
.toString() // Generate text in standard ISO 8601 format.
2020-12-31
org.threeten.extra.YearQuarter
The ThreeTen-Extra library provides classes that extend the functionality of the java.time classes built into Java 8 and later. One of its classes is YearQuarter to represent a specific quarter in a specific year. The quarters are defined by calendar-year: Jan-Mar, Apr-June, July-Sept, Oct-Dec.
LocalDate localDate = LocalDate.of( 2020 , Month.SEPTEMBER , 30 ) ;
YearQuarter yearQuarter = YearQuarter.from( localDate ) ;
Move to the next quarter by adding one quarter to our current year-quarter.
The java.time and ThreeTen-Extra classes use immutable objects. So rather than alter ("mutate") the original object, when adding we produce a new object.
YearQuarter followingYearQuarter = yearQuarter.plusQuarters( 1 ) ;
Determine the last day of that quarter.
LocalDate lastDateOfFollowingYearQuarter = followingYearQuarter.atEndOfQuarter() ;
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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, Java SE 11, and later - 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
Most 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.
Here is my version (hopefully more readable) of finding the last day of next quarter for any date:
public LocalDate lastDayOfNextQuarter(LocalDate date) {
Month firstMonthOfCurrentQuarter = date.getMonth().firstMonthOfQuarter();
LocalDate lastMonthOfCurrentQuarter = date.with(firstMonthOfCurrentQuarter.plus(2));
LocalDate lastMonthOfNextQuarter = lastMonthOfCurrentQuarter.plusMonths(3);
return lastMonthOfNextQuarter.with(lastDayOfMonth());
}
And a corresponding test method:
#ParameterizedTest
#CsvSource({"2020-01-01,2020-06-30", "2020-02-01,2020-06-30", "2020-03-01,2020-06-30", "2020-04-10,2020-09-30",
"2020-05-10,2020-09-30", "2020-06-10,2020-09-30", "2020-07-20,2020-12-31", "2020-08-20,2020-12-31",
"2020-09-30,2020-12-31", "2020-10-30,2021-03-31", "2020-11-30,2021-03-31", "2020-12-31,2021-03-31"})
public void testLastDayOfNextQuarter(LocalDate input, LocalDate expected) {
LocalDate result = timeUtils.lastDayOfNextQuarter(input);
assertEquals(expected, result);
}
You can manipulate quarter easily with TemporalAdjusters. See below:
LocalDate localDate = LocalDate.now();
LocalDate firstDayOfQuarter = localDate.with(IsoFields.DAY_OF_QUARTER, 1);
System.out.println(firstDayOfQuarter);
LocalDate lastDayOfQuarter = firstDayOfQuarter.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
System.out.println(lastDayOfQuarter);
LocalDate firstDateOfNextQuarter = lastDayOfQuarter.plusDays(1);
LocalDate lastDayOfNextQuarter = firstDateOfNextQuarter.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
System.out.println(lastDayOfNextQuarter);
Output:
2020-01-01
2020-03-31
2020-06-30
You can use a Calendar instance to get the last day of the month.
String str = "30-12-20";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");
Date date = format.parse(str);
Date newDate = DateUtils.addMonths(date, 3);
Calendar cal = new GregorianCalendar();
cal.setTime(newDate);
System.out.println(cal.getActualMaximum(Calendar.DAY_OF_MONTH));
We have a java code snippet here
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
Date date = new Date();
int days = 5;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date.getTime() + (days*86400000));
System.out.println(strDate);
}
}
to add n no. of days to today's date. The result will be correct upto n=24 but gives previous month' after n=24. Why it is so?
The problem is the the int is overflowing
consider
int days = 25;
int d = days*86400000;
System.out.println(d);
try
int days = 25;
long d = days*86400000L;
System.out.println(d);
tl;dr
LocalDate // Represent a date-only, without a time-of-day and without a time zone.
.now() // Capture the current date, as seen through your JVM’s current default time zone. Better to pass a `ZoneId` as the optional argument.
.plusDays( 5 ) // Add five days, returning a new `LocalDate` object. Per the Immutable Objects pattern, a new object is produced rather than changing (“mutating”) the original.
.format( // Generate text representing the date value of our `LocalDate` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Define a formatting pattern to suit your taste. Or call the `.ofLocalized…` methods to localize automatically.
) // Returns a `String`.
java.time
Date class represents a moment in UTC, a date with a time-of-day, and an offset-from-UTC of zero. Wrong class to use when working with date-only values.
Avoid using the terrible old legacy date-time classes such as Calendar, Date, and SimpleDateFormat. These classes were supplanted years ago by the java.time classes.
Do not track days as a count of seconds or milliseconds. Days are not always 24 hours long, and years are not always 365 days long.
LocalDate
Instead, use LocalDate class.
LocalDate today = LocalDate.now() ;
LocalDate later = today.plusDays( 5 ) ;
Convert
Best to avoid the legacy classes altogether. But if you must interoperate with old code not yet updated to java.time classes, you can convert back-and-forth. Call new methods added to the old classes.
For Date you need to add a time-of-day. I expect you will want to go with the first moment of the day. And I'll assume you want to frame the date as UTC rather than a time zone. We must go through a OffsetDateTime object to add the time-of-day and offset. For the offset, we use the constant ZoneOffset.UTC. Then we extract the more basic Instant class object to convert to a java.util.Date.
OffsetDateTime odt = OffsetDateTime.of( later , LocalTime.MIN , ZoneOffset.UTC ) ; // Combine the date with time-of-day and with an offset-from-UTC.
Instant instant = odt.toInstant() ; // Convert to the more basic `Instant` class, a moment in UTC, always UTC by definition.
java.util.Date d = java.util.Date.from( instant ) ; // Convert from modern class to legacy class.
Going the other direction:
Instant instant = d.toInstant() ; // Convert from legacy class to modern 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, Java SE 11, and later - 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
Most 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.
Use days*86400000L to make this a long calculation otherwise the int value overflows.
Try this one in your code:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, 5);
strDate = formatter.format(cal.getTime());
I am new to Java and couldnt retrieve the month while using the below code instead month value is set to 0. Please advise the mistakes that i have done here.
*
for(int i=0;i<this.input.size();i++)
{
SimpleDateFormat sf = new SimpleDateFormat("dd/mm/yyyy");
Date purchasedate;
try {
String details = input.get(i);
String[] detailsarr = details.split(",");
purchasedate = sf.parse(detailsarr[1]);
Calendar cal = Calendar.getInstance();
cal.setTime(purchasedate);
int month = cal.get(Calendar.MONTH);
*
After getting the above month as an integer, Could you please advise if there is anyway to print the above month value as "MMM" format?
tl;dr
LocalDate.parse( // Represent a date-only value, without time-of-day and without time zone.
"23/01/2018" , // Tip: Use standard ISO 8601 formats rather than this localized format for data-exchange of date-time values.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
) // Return a `LocalDate` object.
.getMonth() // Return a `Month` enum object representing the month of this date.
.getDisplayName( // Automatically localize, generating text of the name of this month.
TextStyle.SHORT , // Specify (a) how long or abbreviated, and (b) specify whether used in stand-alone or combo context linguistically (irrelevant in English).
Locale.US // Specify the human language and cultural norms to use in translation.
) // Returns a `String`.
See this code run live at IdeOne.com.
Jan
java.time
The modern approach uses the java.time classes that supplanted the terrible Date/Calendar/SimpleDateFormat classes.
ISO 8601
Tip: When exchanging date-time values as text, use the ISO 8601 standard formats rather than using text meant for presentation to humans. For a date-only value, that would be YYYY-MM-DD such as 2018-01-23.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate ld = LocalDate.parse( "23/01/2018" , f ) ;
Month enum
Retrieve the month as a Month enum object.
Month m = ld.getMonth() ;
Localize
Ask that Month enum to generate a String with text of the name of the month. The getDisplayName method can automatically localize for you. To localize, specify:
TextStyle to determine how long or abbreviated should the string be. Note that in some languages you may need to choose stand-alone style depending on context in which you intend to use the result.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Code:
String output = m.getDisplayName( TextStyle.SHORT , Locale.US ) ;
Use enum, not integer
Notice that we had no use of an integer number to represent the month. Using an enum object instead makes our code more self-documenting, ensures valid values, and provides type-safety.
So I strongly recommend passing around Month objects rather than mere int integer numbers. But if you insist, call Month.getMonthValue() to get a number. The numbering is sane, 1-12 for January-December, unlike the legacy classes.
int monthNumber = ld.getMonthValue() ;
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, Java SE 11, and later - 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
Most 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.
java.time
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String dateStringFromInput = "29/08/2018";
LocalDate purchasedate = LocalDate.parse(dateStringFromInput, dateFormatter);
int monthNumber = purchasedate.getMonthValue();
System.out.println("Month number is " + monthNumber);
Running the above snippet gives this output:
Month number is 8
Note that contrary to Calendar LocalDate numbers the months the same way humans do, August is month 8. However to get the month formatted into a standard three letter abbreviation we don’t need the number first:
Locale irish = Locale.forLanguageTag("ga");
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM", irish);
String formattedMonth = purchasedate.format(monthFormatter);
System.out.println("Formatted month: " + formattedMonth);
Formatted month: Lún
Please supply your desired locale where I put Irish/Gaelic. Java knows the month abbreviations in a vast number of languages.
What went wrong in your code?
Apart from using the long outdated date and time classes, SimpleDateFormat, Date and Calendar, format pattern letters are case sensitive (this is true with the modern DateTimeFormatter too). To parse or format a month you need to use uppercase M (which you did correctly in your title). Lowercase m is for minute of the hour. SimpleDateFormat is troublesome here (as all too often): rather than telling you something is wrong through an exception it just tacitly defaults the month to January. Which Calendar in turn returns to you as month 0 because it unnaturally numbers the months from 0 through 11.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Question: Why is January month 0 in Java Calendar?
Simple way of doing this is
Calendar cal = Calendar.getInstance();
Date d = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
System.out.println(sdf.format(d));
In your case modify snippet like below:
SimpleDateFormat sf = new SimpleDateFormat("dd/mm/yyyy");
Date purchasedate;
try {
String details = input.get(i);
String[] detailsarr = details.split(",");
purchasedate = sf.parse(detailsarr[1]);
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
String month = sdf.format(purchasedate);
}
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);
Here is my program, I tried
java.sql.Date logicalDate;
Calendar c = Calendar.getInstance();
c.setTime(logicalDate);
c.add(Calendar.DATE, 1);
The line below is showing an error the constructor Date(date) is undefined
java.sql.Date startDate= new java.sql.Date(c.getTime());
How do I add 1 day to java.sql.Date logicalDate?
Calendar#getTime returns a java.util.Date representation of the Calendar. You really need to use Calendar#getTimeInMillis instead
java.sql.Date startDate= new java.sql.Date(c.getTimeInMillis())
Here is a method
private Date sqlDatePlusDays(Date date, int days) {
return Date.valueOf(date.toLocalDate().plusDays(days));
}
import java.sql.Date;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public static void main(String a[]) {
java.sql.Date todaysDate = new java.sql.Date(new java.util.Date().getTime());
int futureDay =1;
int pastDay=2;
java.sql.Date futureDate = this.addDays(todaysDate, futureDay);
java.sql.Date pastDate = this.subtractDays(todaysDate, pastDay);
System.out.println("futureDate =>>> " + futureDate);
System.out.println("pastDate =>>> " + pastDate);
}
public static Date addDays(Date date, int days) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, days);
return new Date(c.getTimeInMillis());
}
public static Date subtractDays(Date date, int days) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -days);
return new Date(c.getTimeInMillis());
}
}
tl;dr
Never use the terrible legacy classes java.sql.Date, java.util.Calendar, java.util.GregorianCalendar, and java.util.Date. Use only java.time classes.
How do I add 1 day to java.sql.Date logicalDate?
Convert from legacy class java.sql.Date to modern class java.time.LocalDate. Then call plus…/minus… methods to add/subtract days, weeks, months, or years.
myJavaSqlDate.toLocalDate().plusDays( 1 )
If given a Calendar that is actually a GregorianCalendar, and you want only the date, convert to ZonedDateTime and extract a LocalDate.
( (GregorianCalendar) myCal ) // Cast from general `Calendar` to more concrete class `GregorianCalendar`.
.toZonedDateTime() // Convert from the legacy class to the modern `ZonedDateTime` class replacement.
.toLocalDate() // Extract the date only, omitting the time-of-day and the time zone.
.plusWeeks( 1 ) // Returns a `LocalDate` object, a date without a time-of-day and without a time zone.
java.time
The badly designed java.sql.Date class was years ago supplanted by the modern java.time classes with the unanimous adoption of JSR 310. Avoid Calendar class too.
Retrieve from your database with JDBC 4.2 by calling ResultSet::getObject.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
Add a week by calling LocalDate::plusWeeks.
LocalDate weekLater = ld.plusWeeks( 1 ) ;
Write to database by calling PreparedStatement::setObject.
myPreparedStatement.setObject( … , weekLater ) ;
Best to avoid the troublesome legacy date-time classes entirely. But if you need a java.sql.Date object to interoperate with old code not yet updated to java.time, use new conversion methods added to the old classes. Specifically, java.sql.Date.valueOf.
java.sql.Date d = java.sql.Date.valueOf( ld ) ;
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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, Java SE 11, and later - 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
Most 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.
try this :
Calendar cNow = Calendar.getInstance();
Date dNow = cNow.getTime();
cNow.add(Calendar.DATE, 7);
Date dSeven = cNow.getTime();
SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
String dateNow = format.format(dNow);
String dayBefore = format.format(dSeven);
System.out.println(dateNow);
System.out.println(daySeven); //here is your current day + 7
Date date = new Date();
System.out.println(date);