How to get current date time in java

In this post we are going to learn how to get current date time in java.

how to get current date time in java

How to get current date time in java

In date time java program we will be using class GregorianCalendar of java.util package.

import java.util.*;

public class DateTime
{
   public static void main(String[] args)
   {
      int year, month, day;
      int hour, minute, second;
      GregorianCalendar dt = new GregorianCalendar();

      year = dt.get(Calendar.YEAR);
      month = dt.get(Calendar.MONTH);
      day = dt.get(Calendar.DAY_OF_MONTH);

      hour = dt.get(Calendar.HOUR);
      minute = dt.get(Calendar.MINUTE);
      second = dt.get(Calendar.SECOND);

      System.out.println("Current date is " + day + "/" + (month + 1) + "/" + year);
      System.out.println("Current time is " + hour + ":" + minute + ":" + second);

   }
}

Output:

Current date is 29/12/2016
Current time is 7:28:17


java.util.Date

Also read – convert date to string java program

import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class DateTimeDemo 
{
   public static void main(String[] args) 
   {
      DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      Date dt = new Date(0);
      System.out.println(df.format(dt));
   }
}

Output:

2017/09/25 10:07:48


java.util.Calendar

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

public class DateTime 
{
   public static void main(String[] args) 
   { 
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      Calendar ca = Calendar.getInstance();
      System.out.println(sdf.format(ca.getTime()));
   }
}

Output:

2017/09/25 10:07:48


java.time.LocalDateTime

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentDate
{
   public static void main(String[] args)
   {
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
      LocalDateTime ldt = LocalDateTime.now();
      System.out.println(dtf.format(ldt));
   }
}

Output:

2017/09/25 10:07:48


java.time.LocalDate

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateDemo
{
   public static void main(String[] args)
   {
      DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
      LocalDate ld = LocalDate.now();
      System.out.println(dtf.format(ld));
   }
}

Output:

2017/09/25

Related Posts