可以使用SimpleDateFormat类来将字符串日期转换为年、月、日。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        String dateString = '20211231';
        SimpleDateFormat dateFormat = new SimpleDateFormat('yyyyMMdd');
        try {
            Date date = dateFormat.parse(dateString);
            SimpleDateFormat yearFormat = new SimpleDateFormat('yyyy');
            SimpleDateFormat monthFormat = new SimpleDateFormat('MM');
            SimpleDateFormat dayFormat = new SimpleDateFormat('dd');
            
            String year = yearFormat.format(date);
            String month = monthFormat.format(date);
            String day = dayFormat.format(date);
            
            System.out.println('Year: ' + year);
            System.out.println('Month: ' + month);
            System.out.println('Day: ' + day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

输出结果:

Year: 2021
Month: 12
Day: 31
Java 获取字符串日期(yyyyMMdd)的年、月、日

原文地址: https://www.cveoy.top/t/topic/hPkB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录