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);
}
}
后续补充:LocalDatetime转Date
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* @Author: ldj
* @Date: 2023/07/03/17:14
* @Description: LocalDatetime转Date
*/
public class DateTest {
public static void main(String[] args) {
//LocalDateTime --> Data
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(LocalDateTime.now().atZone(zoneId).toInstant());
System.out.println("LocalDateTime = " + localDateTime);
System.out.println("Date = " + date);
//Data --> LocalDateTime
Date date1 = new Date();
Instant instant = date1.toInstant();
LocalDateTime localDateTime1 = instant.atZone(zoneId).toLocalDateTime();
System.out.println("Date1 = " + date1);
System.out.println("LocalDateTime1 = " + localDateTime1);
}
}