可以使用Java的日期时间库来将字符串的年月日转换为年月。以下是一种可能的实现方式:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String dateString = "2022-01-01";
        
        LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.ISO_DATE);
        String yearMonth = date.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        
        System.out.println(yearMonth); // Output: 2022-01
    }
}

在上面的代码中,我们首先使用LocalDate.parse方法将字符串解析为LocalDate对象。然后,我们使用DateTimeFormatter.ofPattern方法创建一个格式化器,并指定输出的格式为"yyyy-MM"。最后,我们使用format方法将LocalDate对象格式化为指定格式的字符串,从而得到年月信息。

请注意,上述代码中使用的日期格式为"yyyy-MM-dd",如果输入字符串中包含了具体的日,则可以直接使用该格式解析日期字符串。如果输入字符串只包含年月信息,则可以使用"yyyy-MM"格式解析

Java把字符串的年月日变成年月

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

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