特定格式的 JavaFX DatePicker getValue

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26831978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:22:37  来源:igfitidea点击:

JavaFX DatePicker getValue in a specific format

javadatedatepickerjavafx

提问by Dushyant Patel

I am currently using Scene Builder to make javafx scenes. I want to get value from the date picker in specific format. Simply using datePicker.getValue() returns date value in yyyy-mm-dd form. I want it in MMM dd, yyyy form. Can anybody help me with that?

我目前正在使用 Scene Builder 制作 javafx 场景。我想从特定格式的日期选择器中获取价值。只需使用 datePicker.getValue() 以 yyyy-mm-dd 形式返回日期值。我想要 MMM dd,yyyy 形式。有人可以帮我吗?

The current complete datePickerController code is this

当前完整的 datePickerController 代码是这样的

package date.picker;

import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.util.StringConverter;

/**
 * FXML Controller class
 *
 * @author Dushyant Patel
 */
public class DatePickerController implements Initializable {

@FXML
private TextField display;
@FXML
private DatePicker datePicker;
@FXML
private Button getDateBtn;
@FXML
private Button setDateBtn;

@FXML
private void getDateAction(ActionEvent event) {

    LocalDate date = datePicker.getValue();
    if (date != null) {
        display.setText(date.toString());
    } else {
        display.setText("");
    }
}

@FXML
private void datePickerAction(ActionEvent event) {
    LocalDate date = datePicker.getValue();
    if (date != null) {
        display.setText(date.toString());
    } else {
        display.setText("");
    }
}

@FXML
private void setDateAction(ActionEvent event) {
    if (!display.getText().trim().equals("")) {
        if (display.getText().length() != 10) {
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle("Error Dialog");
            alert.setHeaderText("Date Error");
            alert.setContentText("Please type date in the correct date format!");

            alert.showAndWait();
        } else {
            LocalDate date = LocalDate.parse(display.getText());
            datePicker.setValue(date);
        }
    } else {
        datePicker.setValue(null);
    }

}

/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    String pattern = "MMM dd, yyyy";
    StringConverter converter = new StringConverter<LocalDate>() {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);

        @Override
        public String toString(LocalDate date) {
            if (date != null) {
                return dateFormatter.format(date);
            } else {
                return "";
            }
        }

        @Override
        public LocalDate fromString(String string) {
            if (string != null && !string.isEmpty()) {
                return LocalDate.parse(string, dateFormatter);
            } else {
                return null;
            }
        }
    };

    datePicker.setConverter(converter);
}

}

回答by Jens-Peter Haack

Use the SimleDateFormat:

使用 SimleDateFormat:

    SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");
    setText(format.format(date));

Oops... LocalDate is not Date....

糟糕... LocalDate 不是日期....

   String date(LocalDate date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy");
        return date.format(formatter);
    }

回答by James_D

Create a DateTimeFormatterwith the pattern you specified (the syntax you gave for the pattern is exactly correct; the docs go into lots of detail on the pattern syntax).

DateTimeFormatter使用您指定的模式创建一个(您为模式提供的语法完全正确;文档详细介绍了模式语法)。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy");

// ...

LocalDate date = datePicker.getValue();
if (date != null) {
    display.setText(formatter.format(date));
} else {
    display.setText("");
}

回答by Reegan Miranda

DataPickerrefer converter in datapicker

DataPicker参考datapicker 中的转换器

 datePicker.setConverter(new StringConverter<LocalDate>() {
 String pattern = "yyyy-MM-dd";
 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);

 {
     datePicker.setPromptText(pattern.toLowerCase());
 }

 @Override public String toString(LocalDate date) {
     if (date != null) {
         return dateFormatter.format(date);
     } else {
         return "";
     }
 }

 @Override public LocalDate fromString(String string) {
     if (string != null && !string.isEmpty()) {
         return LocalDate.parse(string, dateFormatter);
     } else {
         return null;
     }
 }
});

回答by Waxren

Using setConverter will not change the format of .getValue() method which you used to get the value of DatePicker setConverter will only change the displayed date on the DatePicker.

使用 setConverter 不会更改用于获取 DatePicker 值的 .getValue() 方法的格式 setConverter 只会更改 DatePicker 上显示的日期。

For Example to get DatePicker value :-

例如获取 DatePicker 值:-

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy",Locale.US);
String formattedValue = (myDatePicker.getValue()).format(formatter);

And to set the value of the DatePicker

并设置 DatePicker 的值

String dateValue = "01 12, 2015";
myDatePicker.setValue(LocalDate.parse(dateValue,formatter));

回答by Gravity Grave

The docsprovide a great example for this. Just make sure your controller implements Initializableand then initialize it like this:

文档提供了一个很好的例子。只需确保您的控制器实现Initializable然后像这样初始化它:

public class MyController implements Initializable {

  @FXML
  private DatePicker myDatePicker;

  @Override
  public void initialize(URL location, ResourceBundle resources) {

    myDatePicker.setConverter(
        new StringConverter<>() {
          final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

          @Override
          public String toString(LocalDate date) {
            return (date != null) ? dateFormatter.format(date) : "";
          }

          @Override
          public LocalDate fromString(String string) {
            return (string != null && !string.isEmpty())
                ? LocalDate.parse(string, dateFormatter)
                : null;
          }
        });

  }

}