Simple Calendar Date Picker

For my university assignment a small and useful date picker which only picks up weekdays. Moreover it has previous and next buttons which will provide pre and next dates.

I’ve quickly designed a built-in Swing using netbeans whereas I’ve developed my project.

When the application is fire, current day’s date is printed in the textbox which has been disabled to manipulate the value in the element

and Since it does not allow to pick previous day’s date, also previous button is disabled as well

simpledatepickerInitial

When the Next day is pressed, the next value is assigned to the textbox and previous button is set to enabled.

Furthermore when you reach current date, the previous button is set to disabled back again.

simpledatepickerNext

Code

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tugrulaslan.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JOptionPane;

/**
 *
 * @author Tugrul
 */
public class SimpleDatePicker extends javax.swing.JFrame {

    /**
     * Creates new form SimpleDatePicker
     */
    public SimpleDatePicker() {
        initComponents();
        txtDate.setText(getTodaysFormattedDate());
        btnPrev.setEnabled(false);
    }
    
    public String getTodaysFormattedDate() {
        return new SimpleDateFormat("dd-MM-yyyy").format(new java.util.Date());
    }
    
    public Date convertStringDatetoDate(String formattedDate) {
        Date date = new Date();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
            date = simpleDateFormat.parse(formattedDate);
        } catch (ParseException ex) {
            System.err.println("convertFormattedtoDate " + ex);
        }
        return date;
    }
    
    public String convertDateToStringDate(Date date) {
        return new SimpleDateFormat("dd-MM-yyyy").format(date);
    }
    
    public boolean isDateValue(String dateValue) {
        Date date = new Date();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
            date = simpleDateFormat.parse(dateValue);
            return true;
        } catch (ParseException ex) {
            return false;
        }
    }
    
    public Date getPreviousDay(Date currentDate) {
        /*This function only return a weekday, weedays are excluded*/
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.DATE, -1);
        if (isWeekday(calendar.getTime())) {
            date = calendar.getTime();
        } else {
            date = getPreviousDay(calendar.getTime());
        }
        return date;
    }
    
    public Date getNextDay(Date currentDate) {
        /*This function only return a weekday, weedays are excluded*/
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.DATE, 1);
        //check whether the next day value isn't a week day
        if (isWeekday(calendar.getTime())) {
            date = calendar.getTime();
        } else {
            date = getNextDay(calendar.getTime());
        }
        return date;
    }
    
    public boolean isWeekday(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
            return true;
        } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
            return true;
        } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
            return true;
        } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
            return true;
        } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        btnPrev = new javax.swing.JButton();
        txtDate = new javax.swing.JTextField();
        btnNext = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnPrev.setText("Previous");
        btnPrev.setActionCommand("Previous Day");
        btnPrev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrevActionPerformed(evt);
            }
        });

        txtDate.setEditable(false);
        txtDate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtDateActionPerformed(evt);
            }
        });

        btnNext.setText("Next Day");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnPrev)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnNext))
                    .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(txtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPrev)
                    .addComponent(btnNext))
                .addContainerGap(42, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void txtDateActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {                                        
        //Acquire current value
        String currentSelectedDateString = String.valueOf(txtDate.getText());
        Date currentSelectedDate;
        Date nextDateValue;
        
        currentSelectedDate = convertStringDatetoDate(currentSelectedDateString);
        nextDateValue = getNextDay(currentSelectedDate);
        txtDate.setText(convertDateToStringDate(nextDateValue));

        //Enable previous button
        btnPrev.setEnabled(true);
    }                                       

    private void btnPrevActionPerformed(java.awt.event.ActionEvent evt) {                                        
        //Acquire current value
        String currentSelectedDateString = String.valueOf(txtDate.getText());;
        Date currentSelectedDate;
        Date previousDateValue;
        
        currentSelectedDate = convertStringDatetoDate(currentSelectedDateString);
        previousDateValue = getPreviousDay(currentSelectedDate);
        txtDate.setText(convertDateToStringDate(previousDateValue));
        //if previous date is equal to today's date disable the button
        if (convertDateToStringDate(previousDateValue).equals(getTodaysFormattedDate())) {
            btnPrev.setEnabled(false);
        }
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SimpleDatePicker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SimpleDatePicker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SimpleDatePicker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SimpleDatePicker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SimpleDatePicker().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnPrev;
    private javax.swing.JTextField txtDate;
    // End of variables declaration                   
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *