可以使用 Java 的 SimpleDateFormat 类来实现。以下是一个示例代码:

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

public class DateUtils {

    public static void main(String[] args) {
        String dateString = '20220926';
        try {
            Date date = parseDate(dateString, 'yyyyMMdd');
            int year = getYear(date);
            int month = getMonth(date);
            int day = getDay(date);
            System.out.println('Year: ' + year);
            System.out.println('Month: ' + month);
            System.out.println('Day: ' + day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public static Date parseDate(String dateString, String format) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.parse(dateString);
    }

    public static int getYear(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat('yyyy');
        return Integer.parseInt(sdf.format(date));
    }

    public static int getMonth(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat('MM');
        return Integer.parseInt(sdf.format(date));
    }

    public static int getDay(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat('dd');
        return Integer.parseInt(sdf.format(date));
    }
}

main 方法中,我们传入了一个字符串日期 '20220926' 和对应的格式 'yyyyMMdd'。通过调用 parseDate 方法,我们将字符串转化为 Date 对象。然后,我们使用 getYeargetMonthgetDay 方法,将 Date 对象转化为 int 类型的年、月和日。

输出结果如下:

Year: 2022
Month: 09
Day: 26
Java 获取字符串日期 (yyyyMMdd) 的年月日

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

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