How to convert Date to String in Java

How to convert Date to String in Java

Approach : Using toString and valueOf() method

Java


import java.util.Date;

public class DateToString {
    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d.toString());
        System.out.println(String.valueOf(d));
    }
}

Output:


Fri Apr 02 22:54:45 IST 2021
Fri Apr 02 22:54:45 IST 2021

Approach: Using SimpleDateFormat

Java



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

public class DateToString {
    public static void main(String[] args) {
        String pattern = "MM/dd/yyyy HH:mm:ss";

        SimpleDateFormat df = new SimpleDateFormat(pattern);

        Date today = Calendar.getInstance().getTime();
        String todayAsString = df.format(today);

        System.out.println("Today is: " + todayAsString);
    }
}

Output:


Today is: 04/02/2021 22:57:29

No comments:

Post a Comment