java Calendar 格式化yyyy-MM-dd
要将日期格式化为yyyy-MM-dd,可以使用SimpleDateFormat类来实现。以下是一个例子:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
在上面的例子中,我们首先获取当前的Calendar实例,并将其转换为Date对象。然后,我们创建一个SimpleDateFormat对象,并将日期格式模式设置为"yyyy-MM-dd"。最后,我们使用format()方法将日期格式化为指定的格式,并将结果存储在字符串变量formattedDate中。最后,我们将格式化后的日期打印出来。
输出将是类似于"2022-01-01"的格式化日期字符串
原文地址: https://www.cveoy.top/t/topic/iCN8 著作权归作者所有。请勿转载和采集!