Mein Datum der Eingabezeichenfolge lautet wie folgt:
String date = "1/13/2012";
Ich bekomme den Monat wie folgt:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
String month = new SimpleDateFormat("MM").format(convertedDate);
Aber wie bekomme ich den letzten Kalendertag des Monats in einem bestimmten String-Datum?
Beispiel: für einen String "1/13/2012"
muss die Ausgabe "1/31/2012"
sein.
Mit convertedDate.getMonth().length(convertedDate.isLeapYear())
, wobei convertedDate
eine Instanz von LocalDate
ist.
String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
convertedDate.getMonth().length(convertedDate.isLeapYear()));
Mit der getActualMaximum
Methode von Java.util.Calendar
:
String date = "1/13/2012";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
Das sieht nach Ihren Bedürfnissen aus:
http://obscuredclarity.blogspot.de/2010/08/get-last-day-of-month-date-object-in.html
code:
import Java.text.DateFormat;
import Java.text.DateFormat;
import Java.text.SimpleDateFormat;
import Java.util.Calendar;
import Java.util.Date;
//Java 1.4+ Compatible
//
// The following example code demonstrates how to get
// a Date object representing the last day of the month
// relative to a given Date object.
public class GetLastDayOfMonth {
public static void main(String[] args) {
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today : " + sdf.format(today));
System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));
}
}
Ausgabe:
Today : 2010-08-03
Last Day of Month: 2010-08-31
Mit Java 8
DateTime
/LocalDateTime
:
String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
ValueRange range = date.range(ChronoField.DAY_OF_MONTH);
Long max = range.getMaximum();
LocalDate newDate = date.withDayOfMonth(max.intValue());
System.out.println(newDate);
OR
String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
LocalDate newDate = date.withDayOfMonth(date.getMonth().length(date.isLeapYear()));
System.out.println(newDate);
Ausgabe:
2012-01-31
LocalDateTime
sollte anstelle vonLocalDate
verwendet werden, wenn in Ihrer Datumszeichenfolge Zeitangaben vorhanden sind. I.E.2015/07/22 16:49
Mit Java 8 Java.time.LocalDate
String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date,DateTimeFormatter.ofPattern("M/dd/yyyy"));
.with(TemporalAdjusters.lastDayOfMonth());
YearMonth // Represent the year and month, without a date and without a time zone.
.from( // Extract the year and month from a `LocalDate` (a year-month-day).
LocalDate // Represent a date without a time-of-day and without a time zone.
.parse( // Get a date from an input string.
"1/13/2012" , // Poor choice of format for a date. Educate the source of your data about the standard ISO 8601 formats to be used when exchanging date-time values as text.
DateTimeFormatter.ofPattern( "M/d/uuuu" ) // Specify a formatting pattern by which to parse the input string.
) // Returns a `LocalDate` object.
) // Returns a `YearMonth` object.
.atEndOfMonth() // Determines the last day of the month for that particular year-month, and returns a `LocalDate` object.
.toString() // Generate text representing the value of that `LocalDate` object using standard ISO 8601 format.
Siehe dies Code wird live auf IdeOne.com ausgeführt .
2012-01-31
YearMonth
Die Klasse YearMonth
macht dies einfach. Die Methode atEndOfMonth
gibt ein LocalDate
zurück. Das Schaltjahr im Februar wird berücksichtigt.
Definieren Sie zunächst ein Formatierungsmuster, das Ihrer Zeichenfolge entspricht.
DateTimeFormatter f = DateTimeFormatter.ofPattern ("M/d/uuuu");
Verwenden Sie diesen Formatierer, um ein LocalDate
aus der Zeichenfolgeneingabe abzurufen.
String s = "1/13/2012" ;
LocalDate ld = LocalDate.parse( "1/13/2012" , f ) ;
Dann extrahiere ein YearMonth
Objekt.
YearMonth ym = YearMonth.from( ld ) ;
Bitten Sie YearMonth
, den letzten Tag des Monats in diesem Jahr zu bestimmen, wobei Schaltjahr im Februar berücksichtigt wird.
LocalDate endOfMonth = ym.atEndOfMonth() ;
Generieren Sie Text für dieses Datum im Standardformat ISO 8601.
String output = endOfMonth.toString() ;
Das Java.time Framework ist in Java 8 und höher eingebaut. Diese Klassen verdrängen das lästige alte legacy Datum/Uhrzeit-Klassen wie Java.util.Date
, Calendar
, & SimpleDateFormat
.
Das Projekt Joda-Time , das sich jetzt im Wartungsmodus befindet, rät zur Migration auf Java.time = Klassen.
Weitere Informationen finden Sie im Oracle Tutorial . Durchsuchen Sie Stack Overflow nach vielen Beispielen und Erklärungen. Spezifikation ist JSR 31 .
Sie können Java.time Objekte direkt mit Ihrer Datenbank austauschen. Verwenden Sie einen JDBC-Treiber , der JDBC 4.2 oder höher entspricht. Keine Notwendigkeit für Zeichenfolgen, keine Notwendigkeit für Java.sql.*
Klassen.
Woher bekommen Sie die Java.time-Klassen?
Das Projekt ThreeTen-Extra erweitert Java.time um zusätzliche Klassen. Dieses Projekt ist ein Testfeld für mögliche zukünftige Ergänzungen von Java.time. Hier finden Sie möglicherweise einige nützliche Klassen wie Interval
, YearWeek
, YearQuarter
, und mehr .
Am einfachsten ist es, eine neue GregorianCalendar
-Instanz zu erstellen, siehe unten:
Calendar cal = new GregorianCalendar(2013, 5, 0);
Date date = cal.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date : " + sdf.format(date));
Ausgabe:
Date : 2013-05-31
Beachtung:
monat Der Wert, der zum Festlegen des MONTH-Kalenderfelds im Kalender verwendet wird. Der Monatswert ist 0-basiert, z. 0 für Januar.
Sie können den folgenden Code verwenden, um den letzten Tag des Monats abzurufen
public static String getLastDayOfTheMonth(String date) {
String lastDayOfTheMonth = "";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
try{
Java.util.Date dt= formatter.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Java.util.Date lastDay = calendar.getTime();
lastDayOfTheMonth = formatter.format(lastDay);
} catch (ParseException e) {
e.printStackTrace();
}
return lastDayOfTheMonth;
}
Java 8 und höher:
import Java.time.LocalDate;
import Java.time.Year;
static int LastDayOfMonth(int Y, int M) {
return LocalDate.of(Y, M, 1).getMonth().length(Year.of(Y).isLeap());
}
vorbehaltlich der Bemerkung von Basil Bourque
import Java.time.YearMonth;
int LastDayOfMonth = YearMonth.of(Y, M).lengthOfMonth();
Sie können die plusMonths und minusDays - Methoden in Java 8 verwenden:
// Parse your date into a LocalDate
LocalDate parsed = LocalDate.parse("1/13/2012", DateTimeFormatter.ofPattern("M/d/yyyy"));
// We only care about its year and month, set the date to first date of that month
LocalDate localDate = LocalDate.of(parsed.getYear(), parsed.getMonth(), 1);
// Add one month, subtract one day
System.out.println(localDate.plusMonths(1).minusDays(1)); // 2012-01-31
public static String getLastDayOfMonth(int year, int month) throws Exception{
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(year+"-"+(month<10?("0"+month):month)+"-01");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
return sdf.format(lastDayOfMonth);
}
public static void main(String[] args) throws Exception{
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 1));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 3));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 4));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 5));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 6));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 7));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 8));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 9));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 10));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 11));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 12));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 1));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 3));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2010, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2011, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2012, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2013, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2014, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2015, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2016, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2019, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2020, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2021, 2));
}
Ausgabe:
Letzter Tag des Monats: 2017-01-31
Letzter Tag des Monats: 2017-02-28
Letzter Tag des Monats: 2017-03-31
Letzter Tag des Monats: 2017-04-30
Letzter Tag des Monats: 2017-05-31
Letzter Tag des Monats: 2017-06-30
Letzter Tag des Monats: 2017-07-31
Letzter Tag des Monats: 2017-08-31
Letzter Tag des Monats: 2017-09-30
Letzter Tag des Monats: 2017-10-31
Letzter Tag des Monats: 30.11.2017
Letzter Tag des Monats: 2017-12-31
Letzter Tag des Monats: 2018-01-31
Letzter Tag des Monats: 2018-02-28
Letzter Tag des Monats: 2018-03-31
Letzter Tag des Monats: 2010-02-28
Letzter Tag des Monats: 2011-02-28
Letzter Tag des Monats: 2012-02-29
Letzter Tag des Monats: 2013-02-28
Letzter Tag des Monats: 2014-02-28
Letzter Tag des Monats: 2015-02-28
Letzter Tag des Monats: 2016-02-29
Letzter Tag des Monats: 2017-02-28
Letzter Tag des Monats: 2018-02-28
Letzter Tag des Monats: 2019-02-28
Letzter Tag des Monats: 2020-02-29
Letzter Tag des Monats: 2021-02-28
Verwenden Sie GregorianCalendar
. Stellen Sie das Datum des Objekts ein und verwenden Sie dann getActualMaximum(Calendar.DAY_IN_MONTH)
.
http://docs.Oracle.com/javase/7/docs/api/Java/util/GregorianCalendar.html#getActualMaximum%28int%29 (war aber in Java 1.4 gleich