日付と呼ばれるLocalDate変数があり、それを印刷すると1988-05-05と表示されます。これを変換して05.May 1988として印刷する必要があります。これを行う方法は?
日付と呼ばれるLocalDate変数があり、それを印刷すると1988-05-05と表示されます。これを変換して05.May 1988として印刷する必要があります。これを行う方法は?
回答:
彼は私が見ることができるものからのJava 8で新たに追加されLOCALDATEで始まるされている場合のSimpleDateFormatは動作しません、あなたがして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'.LLLL yyyy」を使用する必要がある場合があります。
ProgrammersBlockの投稿の助けを借りて、私はこれを思いつきました。私のニーズは少し異なりました。文字列を取得して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));
}
うまくいけば、これは誰かを助けるでしょう、誰かがこのタスクを行うより良い方法を見つけた場合は、入力を追加してください。
LocalDate.parse(rawDate)
!String.format
ここでは完全に間違った形式で使用されており、実際には最初の文字列を返すだけです。これDateTimeFormatter
はまったく使用されていません。parse
のstatic
メソッドですLocalDate
。 formattedDate
でない形式の日付ではなく、さらにString
(問題の要求どおり)
joda libの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'
幸せなコーディング!:)
String
s との間の変換方法の例も含まれています。