Use the toString() method of the Date class to get the string representation of the current date in Java
In Java, we often need to get the string representation of the current date so that it can be used in log records and files. Used in scenarios such as naming. Java provides the Date class, whose toString() method can help us quickly obtain the string form of the current date. This article will introduce how to use the toString() method of the Date class to obtain the string representation of the current date, and attach relevant code examples.
import java.util.Date; public class GetCurrentDateToString { public static void main(String[] args) { // 创建当前日期对象 Date currentDate = new Date(); // 调用toString()方法获取日期的字符串形式 String currentDateStr = currentDate.toString(); // 打印输出日期的字符串形式 System.out.println("当前日期的字符串形式为:" + currentDateStr); } }
In the above sample code, we first create a Date object currentDate, which represents the current date and time. Then, we call the toString() method of the currentDate object to convert the date object into string form and store the result in the currentDateStr variable. Finally, we output the value of currentDateStr to the console through the print output statement.
当前日期的字符串形式为:Mon Mar 01 10:30:20 CST 2022
In the above results, the format of the string follows the default of the Date class Format. Note that the string representation returned by the toString() method of the Date class is subject to localization and may vary based on different systems and locales.
The above is the detailed content of Get string representation of current date in Java using toString() method of Date class. For more information, please follow other related articles on the PHP Chinese website!