Java - date and time

by
Jeremy Canfield |
Updated: March 23 2022
| Java articles
Let's say you've created a class called MyClass.java (in Eclipse in this example).
In this example, the MyClass.java class is in the com.sample.main package. There is a public class called "MyClass", a public method called "main", and a variable called "date". The "date" variable is returned, so that it can be used (such as in a JSP page).
package com.sample.main;
import java.util.Date;
public class MyClass {
public static void main(String args[]) {
Date date = new Date();
System.out.println("Current date and time is : " + date.toString());
}
}
Running this class should return something like this.
The current date and time is Tue Jan 29 09:14:51 CDT 2021
Here is how you can customize the date and time output.
package com.sample.main;
import java.util.Date;
import java.text.*;
public class MyClass {
public static void main(String args[]) {
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("MM/dd/yyyy 'at' hh:mm:ss a");
System.out.println("Current date and time is : " + ft.format(date));
}
}
Which should return something like this.
The current date and time is 01/29/2021 at 09:17:45 AM
Did you find this article helpful?
If so, consider buying me a coffee over at