You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Android中如何获取'Apr 22'格式指定月份的起止日期

Android Java环境下解析指定格式月份获取起止日期实现方案

核心实现逻辑

直接使用JSR310(java.time时间API)实现,避免传统Calendar、SimpleDateFormat存在的线程不安全、边界计算易出错的问题:

  • 输入字符串格式为MMM yy(如Apr 22),解析时必须指定英文Locale,否则非英文系统环境下会解析失败
  • 用YearMonth类承载解析后的年月数据,该类原生提供获取当月首日、末日的API,无需手动判断大小月、闰年2月等边界场景
  • 最终用指定格式器将起止日期格式化为ddMMyyyy字符串输出

完整实现代码

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateUtils {
    // 输入格式:匹配Apr 22这类 月份缩写+两位年份 的格式,固定用英文Locale解析
    private static final DateTimeFormatter INPUT_MONTH_FORMAT = DateTimeFormatter.ofPattern("MMM yy", Locale.ENGLISH);
    // 输出格式:ddMMyyyy
    private static final DateTimeFormatter OUTPUT_DATE_FORMAT = DateTimeFormatter.ofPattern("ddMMyyyy");

    /**
     * 获取指定月份的起止日期
     * @param monthInput 格式为MMM yy的入参,比如"Apr 22"
     * @return 长度为2的字符串数组,索引0是月初日期ddMMyyyy,索引1是月末日期ddMMyyyy
     */
    public static String[] getMonthStartAndEnd(String monthInput) {
        // 1. 解析入参为年月对象
        YearMonth yearMonth = YearMonth.parse(monthInput, INPUT_MONTH_FORMAT);
        // 2. 获取当月第一天
        LocalDate firstDay = yearMonth.atDay(1);
        // 3. 获取当月最后一天,自动处理大小月、闰年2月逻辑
        LocalDate lastDay = yearMonth.atEndOfMonth();
        // 4. 格式化为要求的字符串返回
        return new String[]{
                firstDay.format(OUTPUT_DATE_FORMAT),
                lastDay.format(OUTPUT_DATE_FORMAT)
        };
    }
}

适配说明

  • 如果项目minSdkVersion >= 26,上述代码可以直接运行
  • 如果需要兼容API26以下的版本,只需在模块级build.gradle中开启coreLibraryDesugaring即可,无需引入第三方时间库:
android {
    compileOptions {
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.4'
}

调用示例

// 测试调用
String[] result = getMonthStartAndEnd("Apr 22");
// result[0] = "01042022" (对应2022年4月1日)
// result[1] = "30042022" (对应2022年4月30日)

注意:不要使用无Locale参数的格式化器解析英文月份缩写,否则在中文、日文等非英文系统上会直接抛出解析异常;不要手动计算月末日期,容易在2月、31天月份出现计算错误,YearMonth原生API已经覆盖所有日期边界场景。

内容的提问来源于stack exchange,提问作者T B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 09:06:52