Date和String类型的相互转换(工具类DateTimeUntil的编写)

在日常的工作中date和string的相互转化比较常用,下面介绍一个工具了:

maven的导包如下:


      joda-time
      joda-time
      2.3
    
DateTimeUntil工具类:

package com.mmall.until;

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 Administrator on 2017/10/12.
 */
public class DateTimeUntil {

    //jidaTime
    //String->Date
    //Date->String
    public static final String STANDRAD_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static Date strToDate(String DateTimeStr,String formaStr){
        DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern(formaStr);
        DateTime dateTime = dateTimeFormat.parseDateTime(DateTimeStr);
        return dateTime.toDate();
    }

    public static String dateToStr(Date date,String formaStr){
        if (date==null){
            return StringUtils.EMPTY;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(formaStr);
    }
    //为了方便应用,重载的函数
    public static Date strToDate(String DateTimeStr){
        DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern(STANDRAD_FORMAT);
        DateTime dateTime = dateTimeFormat.parseDateTime(DateTimeStr);
        return dateTime.toDate();
    }

    public static String dateToStr(Date date){
        if (date==null){
            return StringUtils.EMPTY;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(STANDRAD_FORMAT);
    }
}
测试结果如下:

Date和String类型的相互转换(工具类DateTimeUntil的编写)_第1张图片

应用场景:构建viewObject

        productDetailVo.setCreatetime(DateTimeUntil.dateToStr(product.getCreateTime()));
        productDetailVo.setUpdatetime(DateTimeUntil.dateToStr(product.getUpdateTime()));



你可能感兴趣的:(java-web)