Java Get Current Date
There
are many ways to get current date and time in java. There are 3 classes that
can be used to get current date.
- java.util.Date class
- java.sql.Date class
- java.util.Calendar class
1) Get Current Date by java.util.Date class
By
printing the instance of java.util.Date class, you can print current date and
time in java. There are two ways to do so.
1st
way:
1.
java.util.Date date=new java.util.Date();
2. System.out.println(date);
2nd
way:
1.
long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);
Output:
Thu Mar 26 08:22:02 IST 2015
2) Get Current Date by java.sql.Date class
By
printing the instance of java.sql.Date class, you can print current date in
java. It doesn't print time. This date instance is generally used to save
current date in database.
1.
long millis=System.currentTimeMillis();
2. java.sql.Date date=new java.sql.Date(millis);
3. System.out.println(date);
Output:
2015-03-26
3) Get Current Date by java.util.Calendar class
Calendar
class can be used to get the instance of Date class. The getTime() method of
Calendar class returns the instance of java.util.Date. The
Calendar.getInstance() method returns the instance of Calendar class.
1.
Date date=java.util.Calendar.getInstance().getTime();
2. System.out.println(date);
Output:
Thu Mar 26 08:22:02 IST 2015
No comments:
Post a Comment