Java Tutorial
In this tutorial, you will learn how to get current date in Java Swing and JavaFX. It is pretty simple; keep reading to learn more and this tutorial is best for you to learn to get current date in Java.
How to get current date in Java
To get the current time in Java. We will use the SimpleDateFormat
class. SimpleDateFormat class is very easy to learn, especially for beginners. It allows you to format dates using whatever date pattern you like. The SimpleDateFormat
class has both date and time patterns, however we will only look at the Date patterns in this tutorial. You may find out more about the time pattern by clicking here.
To interpret the date pattern. All you have to do is to type a date pattern into theSimpleDateFormat
parameter and then insert the date patterns inside the double quotation. Avoiding the interpretation, you need to place a single quote inside the double quotation. Take a look at the code below.
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
And this is how to avoid interpretation in the SimpleDateFormat
class. Take a look at the example code below.
SimpleDateFormat sdf = new SimpleDateFormat("'Month: 'MMMM");
The word “Month:” will be printed because we placed it inside the single quotation. To learn more about the date patterns in SimpleDateFormat
class, take a look at the table below.
Letter | Date pattern or components | Presentation | Examples |
G | Era designator | Text | AD |
y | Year | Year | 1996; 96 |
Y | Week year | Year | 2009; 09 |
M | Month in year | Month | July; Jul; 07 |
w | Week in year | Number | 27 |
W | Week in month | Number | 2 |
D | Day in year | Number | 189 |
d | Day in month | Number | 10 |
F | Day of week in month | Number | 2 |
E | Day name in week | Text | Tuesday; Tue |
u | Day number of week (1 = Monday, …, 7 = Sunday) | Number | 1 |
That is the date patterns in SimpleDateFormat
class to get current date in Java. I will show you the example to get current date in Java. Take a look at the example code below.
Example
How to get current date in JavaFX
In this example, It will display the current date in Java and it will also work on Java Swing and JavaFX.
//I will place the code inside a method. private void Date(){ SimpleDateFormat sdf = new SimpleDateFormat("'Today is 'MMMM dd, yyyy"); String datenow = sdf.format(new Date()); System.out.print(datenow); }