要将当前时间转换为字符串,您可以使用java.text.SimpleDateFormat类或java.time.format.DateTimeFormatter类。下面是使用这两个类的示例代码:
使用java.text.SimpleDateFormat类:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String formattedDate = formatter.format(date);
System.out.println(formattedDate);
}
}
使用java.time.format.DateTimeFormatter类(Java 8及以上版本):
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.now();
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime);
}
}
以上两个示例代码中,我们先创建了一个日期时间格式化器,然后使用format()方法将当前时间格式化为指定的字符串格式。示例代码中使用的格式为"yyyy-MM-dd HH:mm:ss",您可以根据需要调整格式。
输出结果可能是类似于"2021-03-24 14:45:25"的字符串,具体格式根据您指定的格式而定。
评论 (0)