Time formatting tool

org.joda.timeThis class is used here .
Scene: Because we are generally stored in the database type is datetime, java object that corresponds to a Date (), but we return to the front end of the long integer
such as:

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

Therefore, we have to write a date tool class to transform it.
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"));
    }
}
Published 281 original articles · 50 praises · 450,000 views +

Guess you like

Origin blog.csdn.net/lzh657083979/article/details/79547256