欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mysql时间处理随手笔记

程序员文章站 2022-05-29 21:06:24
...

随手笔记,不喜勿喷
项目中很多时候遇到个种各样的需求,今天就与到一个这样的需求,数据库适用mysql,前台提问,后台回答,前台显示回复用时,这个很简单,就是回答的创建时间减去提问的创建时间,就得到回复时间,回复用时在数据库中用varchar2类型,直接上Mapper文件代码:

    <update id="update">
        UPDATE sbom_question
        <set>
            <if test="question.answerTimeBack !=null and question.answerTimeBack !=''">
                answer_time = DATE_FORMAT(TIMEDIFF(#{question.answerTimeBack}, create_time),'%h小时%i分%s秒'),
            </if>
            <if test="question.questionStatus !=null and question.questionStatus !=''">
                question_status=#{question.questionStatus},
            </if>
            <if test="question.annexUrl !=null and question.annexUrl !=''">
                annex_url=#{question.annexUrl},
            </if>
            <if test="question.sparePartsCarSystem !=null and question.sparePartsCarSystem !=''">
                spare_parts_car_system=#{question.sparePartsCarSystem},
            </if>
            <if test="question.vin !=null and question.vin !=''">
                vin=#{question.vin},
                一部分代码
    </update>

问题描述:
当时间相减时比如 提问时间为2018-11-27 21:50:30 回答时间2018-11-27 21:52:30 那么回复用时正确显示的应该是0小时02分00秒,但是显示的是12小时02分00秒,多出12小时,问题出在上面SQL中

 answer_time = DATE_FORMAT(TIMEDIFF(#{question.answerTimeBack}, create_time),'%h小时%i分%s秒'),

这里面的h,代表的是12小时,改成H就好了,相减之后再格式化下,就转换成字符串类型,存进数据库,还有数据库时间比较,时间是date类型可以直接如下:

 <select id="selectByTime" resultType="me.cf81.onestep.answerCenter.model.Question">
        <choose>
            <when test="updateTime !=null and  updateTime !='' ">
                select
                <include refid="allColumn"/>
                from sbom_question t WHERE t.is_delete =0
                <if test="createTime !=null and createTime !=''">
                    AND date_format(create_time,'%Y-%m-%d') BETWEEN #{createTime} and #{updateTime}
                </if>
            </when>
            <otherwise>
                select
                <include refid="allColumn"/>
                from sbom_question t WHERE t.is_delete =0
                <if test="createTime !=null and createTime !=''">
                    and date_format(create_time,'%Y-%m-%d') = #{createTime}
                </if>
            </otherwise>
        </choose>
    </select>

适用场景,时间段查询,时间段导出等都可以直接 BETWEEN #{createTime} and #{updateTime}

相关标签: mysql 笔记