Date to String conversion in Java

In this post I am going to show you some sample code for converting date to String, getting current date and converting it to specified date format like YYYY-MM-DD, YYYYMMDD and many more format as you wish.

Getting Current Date and display it in yyyy-mm-dd format

public String getCurrentDate() 
{
       String currentDate = "";
       Date d1 = null;
       final Calendar c = Calendar.getInstance();
       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

       mYear = c.get(Calendar.YEAR);
       mMonth = c.get(Calendar.MONTH) + 1;
       mDay = c.get(Calendar.DAY_OF_MONTH);
       currentDate = "" + mYear + "-" + mMonth + "-" + mDay + "";
       try {
              d1 = dateFormat.parse(currentDate);
       } catch (ParseException e) {
              e.printStackTrace();
       }

       return dateFormat.format(d1);
}



Getting Date as a parameter and converting it to specified format 

public String getFormtedDate(String date) {

       String myDate = "";
       Date d1 = null;
       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

       myDate = date;
       try {
              d1 = dateFormat.parse(myDate);
       } catch (ParseException e) {
              e.printStackTrace();
       }

       return dateFormat.format(d1);
}
 

No comments:

Post a Comment