Date Time Manipulation In Java

There are 2 useful classes in java to manipulate dates: java.util.Date and java.util.Calendar. Another useful class to format and parse string dates is java.text.SimpleDateFormat.

Get Current Date

Date date = new Date();
Calendar calendar = Calendar.getInstance();

Convert from/to Date to/from Calendar

Date date = new Date();
Calendar calendar = Calendar.getInstance();

date = calendar.time();
calendar.setTime(date);

Format Date To String

Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
String dateAsString = dateFormat.format(date);
System.out.println(dateAsString);

Parse Date String

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
Date date = dateFormat.parse(dateAsString);

Add/Substact Days to Current Date

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
Calendar calendar = Calendar.getInstance(); // get current date as calendar object
calendar.add(Calendar.DATE, 1);	//Add 1 day to calendar date
calendar.add(Calendar.DATE, -2);	//Substract 2 days to calendar date
String dateAsString = dateformat.format(calendar.getTime());
System.out.println(dateAsString);

Add/Substact Years/Months/Days/Hours/Minutes/Seconds to Current Date

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
Calendar calendar = Calendar.getInstance(); // get current date as calendar object
calendar.add(Calendar.YEAR, 1);	//Add 1 year to calendar date
calendar.add(Calendar.YEAR, -2);	//Substract 2 years to calendar date
calendar.add(Calendar.MONTH, 1);	//Add 1 month to calendar date
calendar.add(Calendar.MONTH, -2);	//Substract 2 months to calendar date
calendar.add(Calendar.DATE, 1);	//Add 1 day to calendar date
calendar.add(Calendar.DATE, -2);	//Substract 2 days to calendar date
calendar.add(Calendar.HOUR, 1);	//Add 1 day to hourr date
calendar.add(Calendar.HOUR, -2);       //Substract 2 hours to calendar date
calendar.add(Calendar.MINUTE, 1);       //Add 1 minute to calendar date
calendar.add(Calendar.MINUTE, -2);      //Substract 2 minutes to calendar date
calendar.add(Calendar.SECOND, 1);       //Add 1 second to calendar date
calendar.add(Calendar.SECOND, -2);     //Substract 2 seconds to calendar date
String dateAsString = dateformat.format(calendar.getTime());
System.out.println(dateAsString);

Did you enjoy this tutorial? Be sure to subscribe to the my RSS feed not to miss my new posts!
... or make it popular on

1 Comments

Leave a Comment.