zoukankan      html  css  js  c++  java
  • springmvc+mybatis 处理时间

    项目结构:


    一、数据库中time的字段为datetime
    1. 数据库设计如图

    2. addNews.jsp

    <%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <c:set var="ctx" value="${pageContext.request.contextPath}"/>
    <script language="javascript" type="text/javascript" src="${ctx }/js/My97DatePicker/WdatePicker.js"></script>
    <table>
    <tr>
    <td align="right">时间:</td>
    <td>
    <input cssClass="Wdate" onfocus="WdatePicker({skin:'whyGreen',dateFmt:'yyyy-MM-dd HH:mm:ss'});" name="newsTime" size="40" value="" />
    </td>
    </tr>
    </table>
    <!--添加其他字段的代码省略-->

    插入时间所使用的控件:My97DatePicker http://www.my97.net/index.asp ,也可以这里下载

    3. News.java

    import java.io.Serializable;
    import java.util.Date;
    
    import org.springframework.format.annotation.DateTimeFormat;
    
    //新闻
    public class News implements Serializable{
        private Integer newsID;
        private String newsTitle;
        private String newsAbstract;
        private String newsAuthor;
        /**
         *  使用@ModelAttribute接收参数时
         *  form表单中有日期,Spring不知道该如何转换,
         *  要在实体类的日期属性上加@DateTimeFormat(pattern="yyyy-MM-dd")注解 
         *  使用@DateTimeFormat格式:这样jsp页面传递过来的String类型的时间  '2018-04-12 19:40:17' 转换为 Date 类型
         */
        @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
        private Date newsTime;//新闻时间
        private String newsContent;
        
        public News(){
            super();
        }
            //setter and getter
    }

    4. NewsMapper.java和NewDynaSqlProvider.java
    (1)NewsMapper.java

    //动态插入新闻
    @SelectProvider(type=NewsDynaSqlProvider.class,method="insertNews")
    void save(News news);

    (2)NewDynaSqlProvider.java

    //动态插入
        public String insertNews(final News news){
            return new SQL(){
                {
                    INSERT_INTO("news");
                    if(news.getNewsTitle() != null && !news.getNewsTitle().equals("")){
                        VALUES("newsTitle", "#{newsTitle}");
                    }
                    if(news.getNewsAbstract() != null && !news.getNewsAbstract().equals("")){
                        VALUES("newsAbstract", "#{newsAbstract}");
                    }
                    if(news.getNewsAuthor() != null && !news.getNewsAuthor().equals("")){
                        VALUES("newsAuthor", "#{newsAuthor}");
                    }
                    if(news.getNewsTime() != null && !news.getNewsTime().equals("")){
                        VALUES("newsTime", "#{newsTime}");
                    }
                    if(news.getNewsContent() != null && !news.getNewsContent().equals("")){
                        VALUES("newsContent", "#{newsContent}");
                    }
                }
            }.toString();
        }

    5. testService.java和testServiceImpl.java

    (1)testService.java

    /**
     * 添加新闻
     * @param News 新闻对象
     */
     void addNews(News news);

    (2)testServiceImpl.java

    @Override
    public void addNews(News news) {
        newsMapper.save(news);
    }

    6. NewsController.java

    @RequestMapping(value="/addNewst")
         public ModelAndView addNewst(
                 String flag,
                 @ModelAttribute News news,
                 ModelAndView mv,
                 HttpSession session){
            if(flag.equals("1")){
                mv.setViewName("addNews");
            }else{
                testService.addNews(news);
                mv.setViewName("redirect:/htNews");
            }
            return mv;
        }

    插入时间除了在News.java中使用@DateTimeFormat设置一下时间格式,在插入语句中跟插入String类型的字段没有区别。

    运行界面:

    7. 查询语句

    //查询所有新闻(包括查询时间)
    @Select("select * from news")
    List<News> findAllNews();

    8. 查询页面获取时间时,也要设置时间格式:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="f" %>
    <!--省略其他代码-->
    <p>
    <f:formatDate value="${news.newsTime }" type="both" dateStyle="long"/>
    </p>
    <!--省略其他代码-->

     <fmt:formatDate> 标签设置时间格式的属性参考:http://www.runoob.com/jsp/jstl-format-formatdate-tag.html

    运行界面:

    另外发现在插入时间2018-04-11 15:54:26时,后台获取的时间并不是2018-04-11 15:54:26的格式,而是Wed Apr 11 15:54:26 CST 2018

    News [newsID = null newsTitle = 新闻标题 newsAbstract = abstract newsTime = Wed Apr 11 15:54:26 CST 2018 newsContent = add time]
    date type: class java.util.Date
    newsTime: Wed Apr 11 15:54:26 CST 2018

    传入的数据时间格式:

    二、数据库中time的字段为timestamp
    1. 数据库中字段属性为timestamp时,可设置自动更新时间
    设置方法:
    (1)用创建数据库时设置

    CREATE TABLE `notices` (
    `noticeID` int(50) NOT NULL AUTO_INCREMENT,
    `noticeName` varchar(100),
    `noticeContent` varchar(500),
    `noticeTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`noticeID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8

    如果希望在更新记录时还能自动更新noticeTime字段为当前时间:

    `noticeTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    (2)在Navicat for MySQL中设置


    2. Notices.java

    import java.io.Serializable;
    import java.util.Date;
    
    public class Notices implements Serializable{
        private Integer noticeID;
        private String noticeName;
        private String noticeContent;
        private Date noticeTime;
        
        public Notices(){
            super();
        }
           //setter and getter
    }

    3. SQL动态插入,在插入内容时,会自动获取当前时间并保存进数据库

         //动态插入公告
            public String insertNotice(final Notices notices){
                
                return new SQL(){
                    {
                        INSERT_INTO("notices");
                        if(notices.getNoticeName() != null && !notices.getNoticeName().equals("")){
                            VALUES("noticeName", "#{noticeName}");
                        }
                        if(notices.getNoticeContent() != null && !notices.getNoticeContent().equals("")){
                            VALUES("noticeContent", "#{noticeContent}");
                        }
                    }
                }.toString();
            }

     三、MySQL中timestamp和datetime的区别

    timestamp

    datetime

    默认格式

    yyyy-MM-dd HH:mm:ss

    时间范围

    '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC

    即1970——2038年

    '1000-01-01 00:00:00' to '9999-12-31 23:59:59'

    即1001——9999年

    时区

    自动时区转化

    不支持时区

    存储

    4字节(空间利用率更高)

    8字节

    默认值

    如果不设置的话,默认值也是null

    null

    参考:https://www.cnblogs.com/zhaoyanghoo/p/5581710.html

  • 相关阅读:
    《图解HTTP》读书笔记
    Python3 官方文档翻译
    Python3 官方文档翻译
    支付宝Payto接口的C#.net实现方法
    updatepanel用法之triggers(局部刷新,全部刷新)使用示例
    SQL Server中解决死锁
    js字符串与16进制互相转换
    文字超出隐藏并显示省略号,表格固定表头,两表格左右对齐,
    SQL Server中行列转换 Pivot UnPivot
    查看SQL Server日志 Part 1
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/8810324.html
Copyright © 2011-2022 走看看