Convert Date to String in Java

To convert Java dates to strings, you can utilize the SimpleDateFormat class.

Here is an example code that converts the current date into a string with a specified format:

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

public class Main {
    public static void main(String[] args) {
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(currentDate);
        
        System.out.println("当前日期转换为字符串格式为:" + dateString);
    }
}

In the example above, begin by creating a Date object to represent the current date, then create a SimpleDateFormat object specifying the date format. Finally, call the format method to convert the date into a string.

bannerAds