java日期格式yyyyMMdd格式化为yyyy-MM
作者:互联网
package cn.tedu.base;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
test1("20220112");
test2("20220112");
test3(new Date());
}
//方法1
public static void test1(String dateStr) {
//yyyyMMdd转yyyy-MM
Date formatDat = null;
try {
formatDat = new SimpleDateFormat("yyyyMMdd").parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
String str = new SimpleDateFormat("yyyy-MM").format(formatDat);
System.out.println("yyyyMMdd转yyyy-MM : " + str);
}
//方法2
public static void test2(String dateStr) {
StringBuffer s1 = new StringBuffer(dateStr).delete(6, 8).insert(4, "-");
System.out.println("yyyyMMdd转yyyy-MM : " + s1.toString());
}
//当前日期
public static void test3(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
String formatDate = simpleDateFormat.format(date);
System.out.println("yyyyMMdd转yyyy-MM : " + formatDate);
}
}
标签:java,String,MM,SimpleDateFormat,yyyy,yyyyMMdd,public 来源: https://blog.csdn.net/dj1955/article/details/122444344