Date类
表示特定的瞬间,精确到毫秒(在java.util.Date包下)
构造方法:
public Date()
表示分配它的时间(精确到毫秒)。
public Date(long date):
创建一个日期对象,指定毫秒值 (需要将long 时间毫秒值转换成Date对象)
public void setTime(long time):
设置毫秒值
public long getTime()
将Date--->long的毫秒值
Date---->String(格式化) String-->Date(解析)
中间的转换:使用中一个中间类:DateFormat,并且DateFormat是一个抽象类,抽象意味着不能实例化,所以应该考虑用它的子类:
SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。
SimpelDateFormat的构造方法:
public SimpleDateFormat(String pattern) :构造一个SimpleDateFormat对象,根据pattern(模式:规则)
SimpleDateFormat XXX = new SimpleDateFormat("xxx年xx月xx日") ;(需要抛出异常)
simpleDateFormat在解析文本格式的时候,里面 模式(规则)一定要和文本格式的模式一直,否则就出现PareseException
package com.JXWork.util;
import com.alibaba.fastjson.JSON;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 接口说明
*
* @author TF12778 2019/10/9 14:36
*/
public class Utils {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
// Date 有个属性是fastTime,其实new一个Date的时候就是获取了当前系统的时间戳(毫秒数)
// long数据类型后面默认加L,否则系统默认当作Integer,会报数据too larger
// mysql中的datetime 对应 Java.util.Date
/**
* 时间戳转成时间字符串
* 例如:1570599496000 转为 "2019-10-09 13:38:16"
*
* @param timeStamp
* @param format 传空默认:"yyyy-MM-dd HH:mm:ss"
* @return
*/
public static String timeStamp2Str(long timeStamp, String format) {
if (timeStamp <= 0) {
// throw new ServiceException("时间戳不能为空", "500");
System.out.print("时间戳不能为空");
return "";
}
if(format == null || format.isEmpty()) {
format = "yyyy-MM-dd HH:mm:ss";
}
Date date = new Date(timeStamp);
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
/**
* 时间戳转成时间字符串
* 例如: "2019-10-09 13:38:16" 转为 1570599496000
*
* @param dateStr "2019-10-09 13:38:16"
* @param format 传空默认:"yyyy-MM-dd HH:mm:ss"
* @return
*/
public static long str2TimeStamp(String dateStr, String format) {
if(dateStr == null || dateStr.length() == 0) {
System.out.print("时间字符串不能为空");
return 0l;
}
if(format == null || format.length() == 0) {
format = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
try {
Date praseDate = dateFormat.parse(dateStr);
long timeStamp = praseDate.getTime();
return timeStamp;
} catch (ParseException e1) {
e1.printStackTrace();
}
return 0l;
}
}