programing

LocalDate를 문자열로 포맷하는 방법?

prostudy 2022. 5. 14. 22:30
반응형

LocalDate를 문자열로 포맷하는 방법?

나는 a를 가지고 있다.LocalDate변수라고 불리는date, 인쇄할 때 1988-05-05로 표시되면 05로 변환해야 한다.1988년 5월.이거 어떻게 하는 거야?

SimpleDateFormat은 Java 8의 새로운 LocalDate로 시작하는 경우 작동하지 않는다.내가 볼 때, 너는 DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html을 사용해야 할 것이다.

LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);

그것은 1988년 5월 5일 인쇄되어야 한다.그 다음 날과 그 달 전에 그 기간을 얻으려면, "dd"를 사용해야 할지도 모른다.LLL Yyyy"

다음과 같이 짧을 수 있음:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

자바.시간

불행하게도 기존의 모든 답변은 결정적인 것을 놓치고 말았다.Locale.

날짜 시간 구문 분석/포맷 유형(예:DateTimeFormatter최신 API 또는SimpleDateFormat레거시 API)의Locale-민감한패턴에 사용된 기호는 다음을 기준으로 텍스트를 인쇄한다.Locale그들과 함께 사용되었어.가 없는 경우Locale, 기본값을 사용한다.LocaleJVM의자세한 내용을 보려면 이 답변을 확인하십시오.

예상 출력의 텍스트,05.May 1988영어로 되어 있기 때문에, 기존의 해결책들은 단순한 우연의 결과로서만 예상된 결과를 산출할 것이다(디폴트(디폴트)Locale영국인 JVM의Locale).

솔루션 사용java.time, 최신 날짜-시간 API*:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(1988, 5, 5);
        final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MMMM uuuu", Locale.ENGLISH);
        String output = dtf.format(date);
        System.out.println(output);
    }
}

출력:

05.May 1988

여기서, 당신은 사용할 수 있다.yyyy대신에uuuu하지만 난 더 좋아 uy.

Trail: Date Time에서 최신 날짜-시간 API에 대해 자세히 알아보십시오.


* 어떤 이유로든 Java 6 또는 Java 7을 고수해야 할 경우 대부분의 Java.time 기능을 Java 6&7에 백업하는 스리텐 백포트를 사용할 수 있다. Android 프로젝트에서 근무 중인데 Android API 수준이 여전히 Java-8을 준수하지 않는 경우, Disugaring을 통해 이용 가능한 Java 8+ APITs를 확인하십시오.Android Project에서 ABP.

System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MMMM yyyy")));

위의 답변은 오늘을 위해 그것을 보여준다.

프로그래머블럭 게시물들의 도움으로 나는 이것을 생각해냈다.나의 요구는 약간 달랐다.스트링을 가져와 LocalDate 개체로 반환해야 했다.이전 캘린더와 SimpleDateFormat을 사용하는 코드를 받았다.조금 더 최신으로 만들고 싶었다.이것이 내가 생각해 낸 것이다.

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;


    void ExampleFormatDate() {

    LocalDate formattedDate = null;  //Declare LocalDate variable to receive the formatted date.
    DateTimeFormatter dateTimeFormatter;  //Declare date formatter
    String rawDate = "2000-01-01";  //Test string that holds a date to format and parse.

    dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;

    //formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
    //First, the rawDate string is formatted according to DateTimeFormatter.  Second, that formatted string is parsed into
    //the LocalDate formattedDate object.
    formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));

}

이것이 누군가에게 도움이 되기를 바라며, 만약 누군가가 이 일을 하는 더 나은 방법을 알게 된다면, 여러분의 의견을 추가하십시오.

Joda 라이브러리에서 LocalDate를 포맷하는 기본 제공 방법이 있다.

import org.joda.time.LocalDate;

LocalDate localDate = LocalDate.now();
String dateFormat = "MM/dd/yyyy";
localDate.toString(dateFormat);

아직 가지고 있지 않은 경우, build.gradle에 추가:

implementation 'joda-time:joda-time:2.9.5'

해피 코딩! :)

이렇게 하는 꽤 좋은 방법은SimpleDateFormat내가 어떻게 하는지 보여줄게:

SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);

변수에서 날짜를 찾으셨습니다.

sdf.format(variable_name);

건배.

참조URL: https://stackoverflow.com/questions/28177370/how-to-format-localdate-to-string

반응형