Programing

주어진 문자열 날짜의 마지막 날 가져 오기

lottogame 2020. 12. 10. 08:26
반응형

주어진 문자열 날짜의 마지막 날 가져 오기


내 입력 문자열 날짜는 다음과 같습니다.

String date = "1/13/2012";

나는 다음과 같이 달을 얻고있다 :

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
String month = new SimpleDateFormat("MM").format(convertedDate);

그러나 주어진 문자열 날짜에서 월의 마지막 날을 어떻게 얻습니까?

예 : 문자열의 "1/13/2012"경우 출력은 "1/31/2012".


Java 8 이상.

사용하여 convertedDate.getMonth().length(convertedDate.isLeapYear())여기서 convertedDate의 인스턴스이다 LocalDate.

String date = "1/13/2012";
LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
convertedDate = convertedDate.withDayOfMonth(
                                convertedDate.getMonth().length(convertedDate.isLeapYear()));

Java 7 이하.

사용 getActualMaximum방법 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));

이것은 귀하의 요구 사항처럼 보입니다.

http://obscuredclarity.blogspot.de/2010/08/get-last-day-of-month-date-object-in.html

암호:

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

} 

산출:

Today            : 2010-08-03  
Last Day of Month: 2010-08-31  

java 8 java.time.LocalDate를 사용하여

String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date,DateTimeFormatter.ofPattern("M/dd/yyyy"));
                               .with(TemporalAdjusters.lastDayOfMonth());

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

또는

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

산출:

2012-01-31

LocalDateTimeLocalDate날짜 문자열에 시간 정보가있는 경우 대신 사용해야 합니다. IE2015/07/22 16:49


tl; dr

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.

코드는 IdeOne.com에서 실시간으로 실행 됩니다.

2012-01-31

YearMonth

YearMonth클래스는 쉽게 만든다. atEndOfMonth메서드는 LocalDate. 2 월의 윤년이 설명됩니다.

먼저 문자열 입력과 일치하도록 형식화 패턴을 정의하십시오.

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "M / d / uuuu");

해당 포맷터를 사용 LocalDate하여 문자열 입력에서 를 가져옵니다 .

String s = "1/13/2012" ;
LocalDate ld = LocalDate.parse( "1/13/2012" , f ) ;

그런 다음 YearMonth개체를 추출 합니다.

YearMonth ym = YearMonth.from( ld ) ;

2 월의 윤년을YearMonth 고려하여 그해의 마지막 날을 결정하도록 요청하십시오 .

LocalDate endOfMonth = ym.atEndOfMonth() ;

표준 ISO 8601 형식으로 해당 날짜를 나타내는 텍스트를 생성합니다.

String output = endOfMonth.toString() ;  

java.time 정보

java.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 이 클래스는 까다로운 기존에 대신 기존 과 같은 날짜 - 시간의 수업을 java.util.Date, Calendar, SimpleDateFormat.

Joda 타임 프로젝트는 지금에 유지 관리 모드 의로 마이그레이션을 조언 java.time의 클래스.

자세한 내용은 Oracle Tutorial을 참조하십시오 . 그리고 많은 예제와 설명을 위해 Stack Overflow를 검색하십시오. 사양은 JSR 310 입니다.

java.time 객체를 데이터베이스와 직접 교환 할 수 있습니다 . JDBC 4.2 이상을 준수 하는 JDBC 드라이버를 사용하십시오 . 문자열이나 클래스 가 필요하지 않습니다 .java.sql.*

java.time 클래스는 어디서 구할 수 있습니까?

ThreeTen - 추가 프로젝트 추가 클래스와 java.time를 확장합니다. 이 프로젝트는 java.time에 향후 추가 될 수있는 가능성을 입증하는 곳입니다. 당신은 여기에 몇 가지 유용한 클래스와 같은 찾을 수 있습니다 Interval, YearWeek, YearQuarter, 그리고 .


가장 간단한 방법은 새 GregorianCalendar인스턴스 를 해석하는 것입니다 . 아래를 참조하십시오.

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

산출:

Date : 2013-05-31

주의:

month 달력에서 MONTH 달력 필드를 설정하는 데 사용되는 값입니다. 월 값은 0부터 시작합니다 (예 : 1 월의 경우 0).


Java 8 이상 :

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

Basil Bourque의 의견에 따라

import java.time.YearMonth;

int LastDayOfMonth = YearMonth.of(Y, M).lengthOfMonth();

다음 코드를 사용하여 해당 월의 마지막 날을 가져올 수 있습니다.

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

사용 GregorianCalendar. 개체의 날짜를 설정 한 다음 getActualMaximum(Calendar.DAY_IN_MONTH).

http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29 (하지만 Java 1.4에서도 동일)


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

output:

Last Day of Month: 2017-01-31
Last Day of Month: 2017-02-28
Last Day of Month: 2017-03-31
Last Day of Month: 2017-04-30
Last Day of Month: 2017-05-31
Last Day of Month: 2017-06-30
Last Day of Month: 2017-07-31
Last Day of Month: 2017-08-31
Last Day of Month: 2017-09-30
Last Day of Month: 2017-10-31
Last Day of Month: 2017-11-30
Last Day of Month: 2017-12-31
Last Day of Month: 2018-01-31
Last Day of Month: 2018-02-28
Last Day of Month: 2018-03-31
Last Day of Month: 2010-02-28
Last Day of Month: 2011-02-28
Last Day of Month: 2012-02-29
Last Day of Month: 2013-02-28
Last Day of Month: 2014-02-28
Last Day of Month: 2015-02-28
Last Day of Month: 2016-02-29
Last Day of Month: 2017-02-28
Last Day of Month: 2018-02-28
Last Day of Month: 2019-02-28
Last Day of Month: 2020-02-29
Last Day of Month: 2021-02-28


You can make use of the plusMonths and minusDays methods in Java 8:

// 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

Works fine for me with this

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone());
    cal.set(Calendar.MONTH, month-1);  
    cal.set(Calendar.YEAR, year);  
    cal.add(Calendar.DATE, -1);  
    cal.set(Calendar.DAY_OF_MONTH, 
    cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTimeInMillis();

I use this one-liner on my JasperServer Reports:

new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(new java.util.Date().format('yyyy') + "-" + (new Integer (new SimpleDateFormat("MM").format(new Date()))+1) + "-01")-1)

Doesn't look nice but works for me. Basically it's adding 1 to the current month, get the first day of that month and subtract one day.

참고URL : https://stackoverflow.com/questions/13624442/getting-last-day-of-the-month-in-a-given-string-date

반응형