Saturday, November 17, 2018

[JAVA] How to Print Date in yyyy-mm-dd format in Java, Class Date

[JAVA] How to Print Date in yyyy-mm-dd format in Java, Class Date

How to Print Date in yyyy-mm-dd format in Java, Class Date

QUESTION

How to Print Date in yyyy-mm-dd format in Java?
How to Print Time in hh:mm:ss format in Java?

ANSWER

One of the Simplest way to print date in format with Java is using Class Date.
The Class Date states a specific point in time.
It is just a container for the number in milliseconds since the UNIX epoch (January 1, 1970 00:00:00.000 GMT)
If the Date object is printed, the result would be this.
Sun Nov 18 12:34:56 GMT 2018
CurrentTime.java
import java.util.Date;

public class CurrentTime {
 public static void main(String[] args) {
  Date today = new Date();
  System.out.println(today);
  // Sun Nov 18 12:34:56 GMT 2018
 }
}
CurrentTime2.java
import java.text.SimpleDateFormat;
import java.util.Date;

public class CurrentTime2 {
 public static void main(String[] args) {
  Date today = new Date();
  System.out.println(today);
  // Sun Nov 18 12:34:56 GMT 2018

  SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
  SimpleDateFormat time = new SimpleDateFormat("hh:mm:ss a");

  System.out.println("Date: "+date.format(today));
  // Date: 2018-11-18
  System.out.println("Time: "+time.format(today));
  // Time: 10:40:22 AM
 }
}


0 개의 λŒ“κΈ€:

Post a Comment