I want to know how I can compare a mysql date to a java fx date picker date. So if I have a datepicker date in MM/DD/YYYY format and a mysql date in YYYY/MM/DD format how do I compare those two inside a query?
I prepared for you small appliaction how to convert Date to LocalDate and set in DatePicker, how to take LocalDate from DatePicker and convert to Date. You can also check that date are the same.
public class Main extends Application {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
private Date dateUtil = sdf.parse("2016/09/25");
public Main() throws ParseException {
}
#Override public void start(Stage primaryStage) throws Exception {
Button button = new Button("Take date from DatePicker");
Label labelCompare = new Label();
Label labelCompare2 = new Label();
DatePicker datePicker = new DatePicker();
//convert Date to LocalDate
LocalDate localDate = dateUtil.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//set in DatePicker
datePicker.setValue(localDate);
VBox hBox = new VBox();
hBox.getChildren().addAll(datePicker, button, labelCompare, labelCompare2);
Scene scene = new Scene(hBox, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
button.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
//Take LocalDate from DatePicker
LocalDate localDate = datePicker.getValue();
//Convert LocalDate to Date
Date dateFromPicker = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
//compare
labelCompare.setText("Compare date: " + dateUtil.compareTo(dateFromPicker));
}
});
}
public static void main(String[] args) {
launch();
}
}
Easiest way:
String searched_date = datePicker.getValue().toString();
Date dateFromPicker = Date.valueOf(searched_date);
Related
I have created JTable having DatePickerCellEditor with DateFormat(dd/MM/yyyy).
The DateFormat is changing when date is selected.
like this :
here's my code :
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
final DatePickerCellEditor dateCellPrev = new DatePickerCellEditor(formatter);
dateCellPrev.addCellEditorListener(new CellEditorListener() {
#Override
public void editingStopped(ChangeEvent arg0) {
dateCellPrev.setFormats(formatter);
}
#Override
public void editingCanceled(ChangeEvent arg0) {
dateCellPrev.setFormats(formatter);
}
});
table.getColumnModel().getColumn(19).setCellEditor(dateCellPrev);
I want to change format to "dd/MM/yyyy" not like format in last picture
I am trying to create a simple checklist with starting dates that responds to a time slider that specifies a date.
Each task has a start date.
Each task checkbox should only be rendered if the task start date has elapsed.
The checklist looks like this on initialize
How do i update the checklist to respond to the time slider?
I understand I need to add a listener somewhere or make a call to update the ui elements in the scene somewhere, but I am unsure where to begin.
I have tried updating the list used to create, but it doesn't update the UI elements because they have already been created.
ProjectChecklist.java
public class ProjectChecklist extends Application {
Group root = new Group();
Scene scene = new Scene(root, 600, 300);
VBox vbox = new VBox();
HBox hbox = new HBox();
ScrollPane scrollPane = new ScrollPane();
taskList = getAllTasks(PROJECT_FILENAME);
todayDate = LocalDate.now();
sliderStartDate = taskList.get(0).getStartDate();
LocalDate sliderEndDate = taskList.get(taskList.size() - 1).getEndDate();
long days = ChronoUnit.DAYS.between(sliderStartDate, sliderEndDate);
long daysFromToday = ChronoUnit.DAYS.between(sliderStartDate, todayDate);
slider = new Slider(0, days, 1);
slider.setValue(daysFromToday);
sliderValue = new Label(LocalDate.now().toString());
slider.setMajorTickUnit(1);
slider.setShowTickLabels(true);
scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
scrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
slider.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
double daysValue = Math.round(newValue.doubleValue());
LocalDate newDate = (sliderStartDate.plusDays((long) daysValue));
slider.setValue(daysValue);
sliderValue.setText(newDate.toString());
}
int taskNumber = 1;
for (ChecklistTask task : taskList) {
if (!task.getStartDate().isAfter(todayDate)) {
CheckBox newCB = new CheckBox();
newCB.setText("task " + taskNumber++ + ": " + task.getDescription());
vbox.getChildren().add(newCB);
}
}
vbox.getChildren().add(slider);
vbox.getChildren().add(sliderValue);
hbox.getChildren().add(vbox);
hbox.setSpacing(40);
hbox.setPadding(new Insets(10, 10, 10, 10));
scrollPane.setContent(hbox);
scrollPane.setPrefSize(600, 300);
scrollPane.setFitToHeight(true);
root.getChildren().add(scrollPane);
primaryStage.setTitle("Bennington checklist");
primaryStage.setScene(scene);
}
public static void main(String args[]) {
launch(args);
runApplication();
}
ChecklistTask.java
import java.time.LocalDate;
import java.util.UUID;
public class ChecklistTask{
private UUID id;
private String description;
private LocalDate startDate;
private LocalDate endDate;
public ChecklistTask() {
this.id = UUID.randomUUID();
}
public UUID getId() {
return id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
}
I would suggest using a ListView which is backed by a FilteredList where the predicate compares the slider value to the ChequelistTask date. Changing the value of the slider will automatically update the predicate for filtering the list where the start date > the selected date of the slider. The filtering will take care of the list being updated accordingly, without having to rebuild the VBox content.
Here's an example of updating a predicate when something changes:
JavaFX FilteredList, filtering based on property of items in the list
LINK TO GUI IMAGE HERE -------> http://imgur.com/uPD0K5S
public class MainMenu extends javax.swing.JFrame {
public MainMenu() {
initComponents();
cmbRoomNumber.setEnabled(false);
jPanel1.setVisible(false);
btnBook.setEnabled(false);
//SETTING COMBOBOXES TO NONE
cmbPhotoId.setSelectedIndex(-1);
cmbStayDuration.setSelectedIndex(-1);
//LABELS VALIDATION
jlblNameVer.setVisible(false);
//SETTING DATE TODAY
Date now = new Date();
//Set date format as you want
SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
this.ftxtCheckinDate.setText(sf.format(now));
}
As you can see i want to add days to Check-out Date(ftxtCheckOutDate) depending on how many days selected in the combobox(cmbStayDuration)
Im using netbeans JFrame
Thanks :)
private void cmbStayDurationActionPerformed(java.awt.event.ActionEvent evt) {
}
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, combobox number);
Basically Calendar class has a function to add days.
Get the date now, get the combo box day, then add it.
For example:
public static void main(String[] args) {
// TODO code application logic here
Calendar c = Calendar.getInstance();
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
c.setTime(d);
System.out.println(sdf.format(c.getTime()));
c.setTime(d);
c.add(Calendar.DATE, 10);
System.out.println(sdf.format(c.getTime()));
}
Output:
05/11/2015
15/11/2015
As for changing the value of Check-out Date form as the ComboBox changes, you can add either an ActionListener to listen to it change.
Example
I have a LWUIT code that supposed to print today date .
The problem with me is the date printed in "Mon dd hh:mm:ss GMT+...... yyyy" format
e.g Thu Nov 28 01:00:00 GMT+03:00 2013
So I have a couple of questions
How to get the format in "yyyy-mon-dd" format.
how to add a day to the today date after conversion to "yyyy-mon-dd" .
Observe that some classes wouldn't work in J2ME like Simpledateformat class.
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
public class myLibrary extends MIDlet {
Form f;
com.sun.lwuit.Calendar cal;
Button b;
public void startApp() {
com.sun.lwuit.Display.init(this);
f = new com.sun.lwuit.Form();
cal = new com.sun.lwuit.Calendar();
b = new Button("Enter");
f.addComponent(cal);
f.addComponent(b);
b.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent acv) {
System.out.println(""+cal.getDate());
}
});
f.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
In order to use the java.lwuit.Calendar class, to get your date in that format you will need to substring the data from the cal.getDate().
for example
System.out.println("DAY " + cal.getDate().toString().substring(0,3));
Doing that, you will get your data and after that reorder them in a String.
To change the Date from the Calendar view you will need to use Calendar.setDate(Date d);
I suggest you to use java.util.Calendar
java.util.Calendar c = Calendar.getInstnace();
c.set(Calendar.DAY_OF_THE_MONTH, day_that_you want);
c.set(Calendar.MONTH, month_that_you want);
c.set(Calendar.YEAR, year_that_you want);
java.lwuit.Calendar cal = new java.lwuit.Calendar();
cal.setDate(c.getDate().getTime());
If you still want to use the Date class, try this code, it will print the tomorrow day
private static final int DAY = 24 * 60 * 60 * 1000;
Date d = new Date(); d.setTime(d.getTime() + DAY);
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
public class myLibrary extends MIDlet {
Form f;
Button b;
public void startApp() {
com.sun.lwuit.Display.init(this);
private static final int DAY =86400000;
f = new com.sun.lwuit.Form();
b = new Button("Enter");
f.addComponent(b);
b.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent acv) {
java.util.Date d = new java.util.Date();
d.setTime(d.getTime() + DAY);
System.out.println(""+ d.toString());
}
});
f.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
Is there any good and free Date AND Time Picker available for Java Swing?
There are a lot date pickers available but no date AND time picker. This is the closest I came across so far: Looking for a date AND time picker
Anybody?
For a time picker you can use a JSpinner and set a JSpinner.DateEditor that only shows the time value.
JSpinner timeSpinner = new JSpinner( new SpinnerDateModel() );
JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(timeSpinner, "HH:mm:ss");
timeSpinner.setEditor(timeEditor);
timeSpinner.setValue(new Date()); // will only show the current time
You can extend the swingx JXDatePicker component:
"JXDatePicker only handles dates without time. Quite often we need to let the user choose a date and a time. This is an example of how to make use JXDatePicker to handle date and time together."
http://wiki.java.net/twiki/bin/view/Javadesktop/JXDateTimePicker
EDIT: This article disappeared from the web, but as SingleShot discovered, it is still available in an internet archive. Just to be sure, here is the full working example:
import org.jdesktop.swingx.calendar.SingleDaySelectionModel;
import org.jdesktop.swingx.JXDatePicker;
import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.DateFormatter;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;
import java.awt.*;
/**
* This is licensed under LGPL. License can be found here: http://www.gnu.org/licenses/lgpl-3.0.txt
*
* This is provided as is. If you have questions please direct them to charlie.hubbard at gmail dot you know what.
*/
public class DateTimePicker extends JXDatePicker {
private JSpinner timeSpinner;
private JPanel timePanel;
private DateFormat timeFormat;
public DateTimePicker() {
super();
getMonthView().setSelectionModel(new SingleDaySelectionModel());
}
public DateTimePicker( Date d ) {
this();
setDate(d);
}
public void commitEdit() throws ParseException {
commitTime();
super.commitEdit();
}
public void cancelEdit() {
super.cancelEdit();
setTimeSpinners();
}
#Override
public JPanel getLinkPanel() {
super.getLinkPanel();
if( timePanel == null ) {
timePanel = createTimePanel();
}
setTimeSpinners();
return timePanel;
}
private JPanel createTimePanel() {
JPanel newPanel = new JPanel();
newPanel.setLayout(new FlowLayout());
//newPanel.add(panelOriginal);
SpinnerDateModel dateModel = new SpinnerDateModel();
timeSpinner = new JSpinner(dateModel);
if( timeFormat == null ) timeFormat = DateFormat.getTimeInstance( DateFormat.SHORT );
updateTextFieldFormat();
newPanel.add(new JLabel( "Time:" ) );
newPanel.add(timeSpinner);
newPanel.setBackground(Color.WHITE);
return newPanel;
}
private void updateTextFieldFormat() {
if( timeSpinner == null ) return;
JFormattedTextField tf = ((JSpinner.DefaultEditor) timeSpinner.getEditor()).getTextField();
DefaultFormatterFactory factory = (DefaultFormatterFactory) tf.getFormatterFactory();
DateFormatter formatter = (DateFormatter) factory.getDefaultFormatter();
// Change the date format to only show the hours
formatter.setFormat( timeFormat );
}
private void commitTime() {
Date date = getDate();
if (date != null) {
Date time = (Date) timeSpinner.getValue();
GregorianCalendar timeCalendar = new GregorianCalendar();
timeCalendar.setTime( time );
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, timeCalendar.get( Calendar.HOUR_OF_DAY ) );
calendar.set(Calendar.MINUTE, timeCalendar.get( Calendar.MINUTE ) );
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date newDate = calendar.getTime();
setDate(newDate);
}
}
private void setTimeSpinners() {
Date date = getDate();
if (date != null) {
timeSpinner.setValue( date );
}
}
public DateFormat getTimeFormat() {
return timeFormat;
}
public void setTimeFormat(DateFormat timeFormat) {
this.timeFormat = timeFormat;
updateTextFieldFormat();
}
public static void main(String[] args) {
Date date = new Date();
JFrame frame = new JFrame();
frame.setTitle("Date Time Picker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setFormats( DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.MEDIUM ) );
dateTimePicker.setTimeFormat( DateFormat.getTimeInstance( DateFormat.MEDIUM ) );
dateTimePicker.setDate(date);
frame.getContentPane().add(dateTimePicker);
frame.pack();
frame.setVisible(true);
}
}
Use the both combined.. that's what i did:
public static JPanel buildDatePanel(String label, Date value) {
JPanel datePanel = new JPanel();
JDateChooser dateChooser = new JDateChooser();
if (value != null) {
dateChooser.setDate(value);
}
for (Component comp : dateChooser.getComponents()) {
if (comp instanceof JTextField) {
((JTextField) comp).setColumns(50);
((JTextField) comp).setEditable(false);
}
}
datePanel.add(dateChooser);
SpinnerModel model = new SpinnerDateModel();
JSpinner timeSpinner = new JSpinner(model);
JComponent editor = new JSpinner.DateEditor(timeSpinner, "HH:mm:ss");
timeSpinner.setEditor(editor);
if(value != null) {
timeSpinner.setValue(value);
}
datePanel.add(timeSpinner);
return datePanel;
}
There is the FLib-JCalendar component with a combined Date and Time Picker.
As you said Date picker is easy, there are many out there.
As for a Time picker, check out how Google Calendar does it when creating a new entry. It allows you to type in anything while at the same time it has a drop down in 30 mins increments. The drop down changes when you change the minutes.
If you need to allow the user to pick seconds, then the best you can do is a typable/drop down combo