时间格式化工具

这里使用的是org.joda.time这个类。
场景:因为我们数据库一般都是存放的是datetime类型,对应的java对象是Date() ,但是我们返回给前端的是长整型
比如:

"status": 0,
  "data": [
    {
      "id": 100006,
      "parentId": 100001,
      "name": "冰箱",
      "status": true,
      "sortOrder": null,
      "createTime": 1490431935000,
      "updateTime": 1490431935000
    },

所以,我们要写一个date工具类,来转化一下。
pom

 <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.3</version>
    </dependency>

DateUtils.java

package com.mmall.untis;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.Date;

/**
 * Created by 敲代码的卡卡罗特
 * on 2018/3/13 21:18.
 */
public class DateUtils {

    private static final String FORMATSTR="yyyy-MM-dd HH:mm:ss";


    //字符串转date
    public static Date strToDate(String str,String formatStr){
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
        DateTime dateTime = dateTimeFormatter.parseDateTime(str);
        return dateTime.toDate();
    }
    //日期转字符串
    public static String dateToString(Date date , String formatStr){
        if (date==null){
            return StringUtils.EMPTY;
        }
        DateTime dateTime = new DateTime(date);
        return  dateTime.toString(formatStr);
    }

    //字符串转date
    public static Date strToDate(String str){
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(FORMATSTR);
        DateTime dateTime = dateTimeFormatter.parseDateTime(str);
        return dateTime.toDate();
    }
    //日期转字符串
    public static String dateToString(Date date ){
        if (date==null){
            return StringUtils.EMPTY;
        }
        DateTime dateTime = new DateTime(date);
        return  dateTime.toString(FORMATSTR);
    }

    public static void main(String[] arg){
        System.out.println(DateUtils.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
        System.out.println(DateUtils.strToDate("2010-11-11 11:11:11","yyyy-MM-dd HH:mm:ss"));
    }
}
发布了281 篇原创文章 · 获赞 50 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/lzh657083979/article/details/79547256