package com.example.statistics.util;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class DateUtil {
/**
* 时间戳转换指定格式
* @param time
* @param format 指定格式
* @return
*/
public String getDateStrByTime(Long time, String format) {
TimeZone timeZoneSH = TimeZone.getTimeZone("Asia/Shanghai");
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
sdf.setTimeZone(timeZoneSH);
Date date;
String dateStr = "";
try {
if (time != null){
date = sdf.parse(sdf.format(time));
dateStr = sdf.format(date);
}
} catch (Exception e) {
e.printStackTrace();
}
return dateStr;
}
/**
* 时间戳转换指定格式(固定格式:yyyy-MM-dd HH:mm:ss)
* @param time
* @return
*/
public String getDateStrByTime(Long time) {
TimeZone timeZoneSH = TimeZone.getTimeZone("Asia/Shanghai");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
sdf.setTimeZone(timeZoneSH);
Date date;
String dateStr = "";
try {
if (time != null){
date = sdf.parse(sdf.format(time));
dateStr = sdf.format(date);
}
} catch (Exception e) {
e.printStackTrace();
}
return dateStr;
}
/**
* 时间转换成时间戳
*/
public Long getDateByLongTime(String time){
Long timeLong=0l;
if(time!=null){
Date date = new Date(time);
timeLong = date.getTime();
}
return timeLong;
}
/**
* 校验上送时间格式是否正确
* @param timeStr
* @return
*/
public boolean checkDate(String timeStr){
boolean pass = true;
SimpleDateFormat sdf = null;
if (timeStr != null && !"".equals(timeStr)){
if (timeStr.contains("-")){
sdf = new SimpleDateFormat("yyyy-MM-dd");
} else {
sdf = new SimpleDateFormat("yyyy/MM/dd");
}
Date date = null;
try {
date = sdf.parse(timeStr);
} catch (Exception e){
pass = false;
}
}
return pass;
}
/**
* 正则表达式进行判断数字类型
*/
public boolean isNumeric(String str) {
//Pattern pattern = Pattern.compile("^-?[0-9]+"); //这个也行
Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");//有小数点也可以
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
}
java 日期转换工具
最新推荐文章于 2024-04-28 11:30:09 发布