Java program to get current Date and Time

This tutorials about Java program to get current date and time. There are different ways to get current date and current time in Java.

Methods for getting current date and time:

Method 1:

Using the package java.util.Date

Syntax: java.util.Date date=new java.util.Date();

Method 2:

Using the package java.sql.Date

Syntax: java.sql.Date date1=new java.sql.Date(System.currentTimeMillis());

Method 3:

Using the package java.time.LocalDate to get local date

Syntax: java.time.LocalDate.now()

Method 4:

Using the package java.time.LocalTime to get local time

Syntax: java.time.LocalTime.now()

Method 5:

Using package java.time.LocalDateTime to get both date and time

Syntax: java.time.LocalDateTime.now()

Method 6:

Using the package java.time.clock

Syntax: java.time.Clock.systemUTC().instant()

Method 7:

Using the package java.time.Calendar

Syntax: Calendar.getInstance().getTime()

Method 8:

The package java.text is used to get date and time in simple date format from calendar object.

Syntax: SimpleDateFormat sdf=new SimpleDateFormat(“dd/MM/yyyy hh:mm:ss”);

DateAndTime.java


package com.candidjava.time;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DateAndTime 
{
public static void main(String[] args)
{
	//using package java.util to get date and time 
	java.util.Date date=new java.util.Date();
	System.out.println("Date:" +date);
	
	//using package java.sql to get date and time
	java.sql.Date date1=new java.sql.Date(System.currentTimeMillis());
	System.out.println("Date1:" +date1);

	//using java.time.LocalDate
	System.out.println(java.time.LocalDate.now());
	
	//using java.time.LocalTime
	System.out.println(java.time.LocalTime.now());
	
	//using java.time.LocalDateTime
	System.out.println(java.time.LocalDateTime.now());
	
	//using java.time.clock 
	System.out.println(java.time.Clock.systemUTC().instant());
	
	//using package java.util.calendar
	System.out.println(Calendar.getInstance().getTime());
	
	//using package java.text
	SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
	String c=sdf..format(Calendar.getInstance().getTime());
	System.out.println(c);
}
}

Output:

Date:Mon Jan 07 13:30:47 IST 2019
Date1:2019-01-07
2019-01-07
13:30:47.401
2019-01-07T13:30:47.401
2019-01-07T08:00:47.401Z
Mon Jan 07 13:30:47 IST 2019
07/01/2019 01:30:47

Leave a Reply

Your email address will not be published. Required fields are marked *