Java时间戳转换工具类
java常用工具类:时间戳与时间相互转换,需要的拿走!
package com.lcry.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 时间戳与时间相互转换工具类
* Created on 2018/12/24.
*
* @author lcry
*/
public class DateAndStampUtil {
/*
* 将时间转换为时间戳
*/
/**
* (int)时间戳转Date
*
* @param timestamp
* @return
*/
public static Date stampForDate(Integer timestamp) {
return new Date((long) timestamp * 1000);
}
/**
* (long)时间戳转Date
*
* @param timestamp
* @return
*/
public static Date longStampForDate(long timestamp) {
return new Date(timestamp);
}
/**
* date转String
*
* @param date
* @return
*/
public static String dateForString(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
/**
* String转Date
*
* @param time
* @return
*/
public static Date stringForDate(String time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* Date转时间戳
*
* @param data
* @return
*/
public static Integer dateForStamp(Date data) {
return (int) (data.getTime() / 1000);
}
/**
* (string)时间转时间戳
*
* @param s
* @return
* @throws ParseException
*/
public static String dateToStamp(String s) throws ParseException {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(s);
long ts = date.getTime();
res = String.valueOf(ts);
return res;
}
/**
* (string)时间戳转日期
*
* @param s
* @return
*/
public static String stampToDate(String s) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(s);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}
}
商业转载请联系作者获得授权,非商业转载请注明本文出处及文章链接