Issue
In my project, I have a page that contains a datepicker
element. I also have a date which is in the form of a string
. I want to display the string (date)
in the field of the datePicker
. Is there any way to do this ?
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public void prevf()
{
String dates="28/12/2002";
LocalDate date=LocalDate.parse(dates);
EndDateF.setValue(date); //Where EndDateF is a datePicker field
}
This had no effect, as the datePicker
(EndDateF
) was still blank.
I tried doing something like this as well:
Date newDate = new SimpleDateFormat("dd/MM/yyyy").parse(date);
But this converts it to Date
, and not LocalDate
.
Is there any way to convert a String
to such a format that can be displayed in the field of the datepicker
?
Solution
This is how you convert a String
to LocalDate
which is of a specific pattern
:
String dateAsString = "28/12/2002";
DateTimeFormatter customDateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate localDate = LocalDate.parse(date, formatter);
And then set the value:
endDateDatePicker.setValue(localDate);
Answered By - Renis1235
Answer Checked By - Willingham (JavaFixing Volunteer)