Date 类型的对象,如果你只想保留 "yyyy-MM-dd" 格式的部分
1.创建一个 SimpleDateFormat 对象,并设置日期格式为 "yyyy-MM-dd"。
import java.text.SimpleDateFormat;
import java.util.Date;
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
2.使用 SimpleDateFormat 对象的 format() 方法将 Date 对象格式化为字符串。
String formattedDate = dateFormat.format(date);
3.完整代码:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = dateFormat.format(date);
System.out.println("日期部分:" + formattedDate);
}
}
Java中格式化Date为yyyy-MM-dd的方法,
该文章展示了如何在Java中使用SimpleDateFormat类将Date对象格式化为yyyy-MM-dd字符串。首先创建一个SimpleDateFormat实例,指定格式,然后调用format()方法处理Date对象,最后打印出格式化后的日期。
4536





