Wednesday, March 16, 2016

Get Current Date/Time As String in Java

Watch Video

The simplest way to get the date and time as a String in Java is to import and use the following classes: Date and SimpleDateFormat. The Date class contains the current Date data and the SimpleDateFormat class allows us to format the date data in a manner we specify.

The following example prints out the current date and time formatted in US date/time notation.

import java.text.SimpleDateFormat;
import java.util.Date;

public class main {
 public static void main(String[] args) {

  SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/y hh:mm:ss a");
  Date thisDate = new Date();
  System.out.println(dateFormat.format(thisDate));

 }

}
Sample Output10/26/2015 06:55:07 PM

Modifying The Date Format

You can modify the date format string when you create the SimpleDateFormat with any of the following:

  • MM - The numerical month of the year
  • dd - The numerical day of the month
  • D - The numerical day of the year
  • W - The numerical week of the month
  • w - The numerical week of the year
  • E - The text format day of the week abbreviation
  • EEEE - The full text format day of the week
  • MMMM - The text format month of the year
  • a - AM or PM
  • H - Numerical hour of the 24 hour day
  • h - Numerical hour as AM/PM from 1-12
  • m - Numerical minute in hour
  • s - Numerical second in minute

For example, you could modify the date format to print out the date in US text format:

SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE MMMM dd, Y. h:mm a");
Date thisDate = new Date();
System.out.println(dateFormat.format(thisDate));
Sample OutputMonday October 26, 2015. 7:09 PM

0 comments:

Post a Comment