Monday, September 14, 2015

How to use the Calendar class

Get the current time stamp using java Calendar

import java.util.Calendar;
class Demostration{
 public static void main(String[]args){
  Calendar calendar=Calendar.getInstance();  
  System.out.println(calendar.getTime());    
 } 
}


To work with Calendar class you will need a little knowledge about Date and DateFormat classes, in the following examples I'll show how to use Date and DateFormat classes

Get the current time stamp using java Date


import java.util.Date;
class Demostration{
 public static void main(String[]args){
  Date date=new Date();
  System.out.println(date);    
 } 
}


By studying above examples you can understand that calendar.getTime() method also returns a new Date class object

Format time stamp using DateFormat, SimpleDateFormat classes


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
class Demostration{
 public static void main(String[]args){
  Date date=new Date();
  DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
  String formattedDate=dateFormat.format(date);
  System.out.println(formattedDate);    
 } 
}

in the next example I'm going to add the time also

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
class Demostration{
 public static void main(String[]args){
  Date date=new Date();
  DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  String formattedDate=dateFormat.format(date);
  System.out.println(formattedDate);    
 } 
}

Try changing the pattern string ("yyyy-MM-dd hh:mm:ss") to some other like
"EEE-MM-dd hh:mm:ss"



No comments:

Post a Comment