This tutorial is divided into three sections as follows:
1) Calculate the number of days between two dates
2) Get the previous day date and the next day date from the given date
3) Compare two dates with each other
You’re reading part 2 pf above mentioned tutorials: Here we are providing an input date in yyyy-MM-dd
format and generating the previous days and next days date from it.
class Demo{ public static void main(String args[]) { /*This is our input date. We will be generating * the previous and next day date of this one */ String fromDate = "2014-01-01"; //split year, month and days from the date using StringBuffer. StringBuffer sBuffer = new StringBuffer(fromDate); String year = sBuffer.substring(2,4); String mon = sBuffer.substring(5,7); String dd = sBuffer.substring(8,10); String modifiedFromDate = dd +'/'+mon+'/'+year; int MILLIS_IN_DAY = 1000 * 60 * 60 * 24; /* Use SimpleDateFormat to get date in the format * as passed in the constructor. This object can be * used to covert date in string format to java.util.Date * and vice versa.*/ java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("dd/MM/yy"); java.util.Date dateSelectedFrom = null; java.util.Date dateNextDate = null; java.util.Date datePreviousDate = null; // convert date present in the String to java.util.Date. try { dateSelectedFrom = dateFormat.parse(modifiedFromDate); } catch(Exception e) { e.printStackTrace(); } //get the next date in String. String nextDate = dateFormat.format(dateSelectedFrom.getTime() + MILLIS_IN_DAY); //get the previous date in String. String previousDate = dateFormat.format(dateSelectedFrom.getTime() - MILLIS_IN_DAY); //get the next date in java.util.Date. try { dateNextDate = dateFormat.parse(nextDate); System.out.println("Next day's date: "+dateNextDate); } catch(Exception e) { e.printStackTrace(); } //get the previous date in java.util.Date. try { datePreviousDate = dateFormat.parse(previousDate); System.out.println("Previous day's date: "+datePreviousDate); } catch(Exception e) { e.printStackTrace(); } } }
Output:
Next day's date: Thu Jan 02 00:00:00 IST 2014 Previous day's date: Tue Dec 31 00:00:00 IST 2013
Leave a Reply