Java Example – Convert Date to String




Java Tutorial for Beginners
Java Tutorial for Beginners

Convert Date to String in Java

In this Java Example we will see How to convert Date to String or how to convert java.util.Date to String in Java.

/**
 * Java Convert Date to String Example
 * Created by codebind.com .
 */

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConvertDateToString {

    public static void main(String args[]) {

        //create new java.util.Date object
        Date date = new Date();

    /*
     * To convert java.util.Date to String, use SimpleDateFormat class.
     */

    /*
     * crate new SimpleDateFormat instance with desired date format.
      * We are going to use yyyy-mm-dd hh:mm:ss here.
     */
        DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");

        //to convert Date to String, use format method of SimpleDateFormat class.
        String strDate = dateFormat.format(date);

        System.out.println("converted Date to String: " + strDate);

    }
}

/*
OUTPUT:
converted Date to String: 2016-59-17 08:59:49
*/

 





Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





3 Comments

  1. The ‘mm’ must to be upper case (“MM”), or it will be interpreted as minutes.
    So instande of “yyyy-mm-dd hh:mm:ss” do “yyyy-MM-dd hh:mm:ss”

Leave a Reply

Your email address will not be published.


*