Muhammad Saim Hashmi Muhammad Saim Hashmi - 4 months ago 8
Java Question

Year in GUI not showing proper year

public class Output extends javax.swing.JFrame {

public Output() {
initComponents();
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("abc.jpg")));
setSize(400, 700);
setLocationRelativeTo(null );
setResizable(false);
setdate();
}
public void setdate(){
ActionListener obj = new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
java.util.Date date = new Date();

Date.setText(date.getDate()+"-"+(1+date.getMonth())+
"-"+date.getYear()+" / "+date.getHours() + ":"
+ date.getMinutes()+ ":" +
date.getSeconds());
}
};
new javax.swing.Timer(1000,obj).start();
}


Whenever I run this code I get every thing OK but while setting year it shows
18-8-116
, while it should show
18-8-16
or
18-8-2016
.

Answer

Date stores the year of a date as years from 1900, hence the 116 (1900 + 116 = 2016).

Most of Date's methods have been deprecated since Java 1.1. Until Java 1.8, you better used Calendar or LocalDate from Joda-Time. Since Java 1.8, Date has been superseded by LocalDate, LocalTime, LocalDateTime and their timezoned counterparts, i.e. ZonedDateTime.

So you might want to use a LocalDate here, i.e.

LocalDate date = LocalDate.of(2016, Month.AUGUST, 18);