1

I've just started to learn java and can't fully understand every step of getting a date (e.g. Calendar.getInstance().get(Calendar.DATE); . Can someone please explain it to me? Sorry if the question is stupid

Jamie Reid
  • 532
  • 2
  • 17

2 Answers2

0

In Java, you can get the current date time via following two classes – Date and Calendar. And, later use SimpleDateFormat class to convert the date into a user friendly format.

Using Date() + SimpleDateFormat():

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2014/08/06 15:59:48

Using Calender() + SimpleDateFormat()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); //2014/08/06 16:00:22

Here's a full example to show you how to use Date() and Calender() classes to get and display the current date time.

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

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

       DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
       //get current date time with Date()
       Date date = new Date();
       System.out.println(dateFormat.format(date));

       //get current date time with Calendar()
       Calendar cal = Calendar.getInstance();
       System.out.println(dateFormat.format(cal.getTime()));

  }
}

Please review the following two manual pages:

Jamie Reid
  • 532
  • 2
  • 17
-1

Full examples provided in the links below:

1)examples

2)gete date and Calendar

The java.util.Calendar.getInstance() method gets a calendar using the specified time zone and specified locale.The point of using getInstance() is that it will take the default locale and time-zone into account when deciding which Calendar implementation to return and how to initialize it.

crAlexander
  • 376
  • 1
  • 2
  • 12
  • its better to add code snippet in answer itself rather than providing links – Raunak Kathuria Feb 28 '15 at 18:41
  • @Raunak Kathuria In this case man the link have obviously examples with explaining.If it is more information needed by the asker i will provide them. – crAlexander Feb 28 '15 at 18:44
  • I have not downvoted relax. just saying so that next person who comes can get an overview of your answer and if more details required he can open link – Raunak Kathuria Feb 28 '15 at 18:46