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

如何将日期部分重置为当月最后一天并保留时间?

当然可以!这是个非常实用的日期处理需求,我给你整理了几种主流编程语言的实现方案,都能完美实现把日期调整为当月最后一天,同时完整保留原时间部分:

Python 实现

可以结合datetime和calendar模块来搞定,核心思路是先拿到原日期的年、月,再获取该月的最后一天,最后替换原日期的“日”部分,时分秒完全保留:

import datetime
import calendar

def set_to_month_end(dt):
    # 获取当月最后一天的数字(比如1月是31,4月是30)
    last_day_num = calendar.monthrange(dt.year, dt.month)[1]
    # 替换原日期的日,保留时分秒
    return dt.replace(day=last_day_num)

# 测试示例
dt1 = datetime.datetime(2018, 1, 2, 23, 0, 0)
dt2 = datetime.datetime(2018, 4, 4, 10, 0, 0)
print(set_to_month_end(dt1))  # 输出: 2018-01-31 23:00:00
print(set_to_month_end(dt2))  # 输出: 2018-04-30 10:00:00

SQL 实现

不同数据库的函数略有差异,这里给你常用的两种:

MySQL

直接用LAST_DAY()获取当月最后一天的日期,再拼接原时间即可:

SELECT CONCAT(LAST_DAY('2018-01-02 23:00:00'), ' ', TIME('2018-01-02 23:00:00')) AS month_end_datetime;
-- 输出: 2018-01-31 23:00:00

SELECT CONCAT(LAST_DAY('2018-04-04 10:00:00'), ' ', TIME('2018-04-04 10:00:00')) AS month_end_datetime;
-- 输出: 2018-04-30 10:00:00

PostgreSQL

先把日期截断到当月第一天,再加一个月减一天得到当月最后一天,最后拼接原时间:

SELECT (DATE_TRUNC('month', '2018-01-02 23:00:00'::TIMESTAMP) + INTERVAL '1 month - 1 day') + TIME('2018-01-02 23:00:00') AS month_end_datetime;
-- 输出: 2018-01-31 23:00:00

SELECT (DATE_TRUNC('month', '2018-04-04 10:00:00'::TIMESTAMP) + INTERVAL '1 month - 1 day') + TIME('2018-04-04 10:00:00') AS month_end_datetime;
-- 输出: 2018-04-30 10:00:00

JavaScript 实现

利用Date对象的特性:先创建下个月的第一天,再减一天得到当月最后一天,最后把原时间的时分秒赋值回去:

function setToMonthEnd(date) {
    const year = date.getFullYear();
    const month = date.getMonth();
    // 生成下个月第一天的日期对象
    const nextMonthFirstDay = new Date(year, month + 1, 1);
    // 减1天得到当月最后一天
    const lastDay = new Date(nextMonthFirstDay - 1);
    // 保留原时间的时分秒和毫秒
    lastDay.setHours(date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
    return lastDay;
}

// 测试示例
const dt1 = new Date('2018-01-02 23:00:00');
const dt2 = new Date('2018-04-04 10:00:00');
// 格式化输出成你要的样式
console.log(setToMonthEnd(dt1).toISOString().slice(0, 19).replace('T', ' ')); // 输出: 2018-01-31 23:00:00
console.log(setToMonthEnd(dt2).toISOString().slice(0, 19).replace('T', ' ')); // 输出: 2018-04-30 10:00:00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:27:53