How to convert date to string in Java?

Hello developers,

I have java.util.Date object and it has to be converted to date format.

How to convert date to string in Java?

Thanks

View Answers

February 9, 2018 at 8:04 PM

Hi,

To convert java.util.Date object into string SimpleDateFormat class is used, and its format() method takes data object.

The format() method performs conversion and returns string date object.

Here is the example program that I developed for you.

package net.roseindia;

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

/**
 * @author Deepak Kumar More tutorials at http://www.roseindia.net
 */
/*
 * In this example we convert current date to String
 */
public class DateToStringConversion {

    public static void main(String[] args) {
        try {
            DateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
            Date date = new java.util.Date();//Current date
            String sDate = fmt.format(date);
            System.out.println("Today is " + sDate);
        } catch (Exception e) {
            System.out.println("Exception :" + e);
        }

    }

}

Check Java Conversion examples.

Thanks









Related Tutorials/Questions & Answers:
Advertisements