时间戳格式转换工具类

版权声明:本文为CSDN博主「月半花开」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_20957669/article/details/103117588

 

在网上找的 觉得比较好用的时间格式转换工具类  拿来当笔记收藏  已标记原文出处

 

复制代码
package com.eticket.Utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
/**
 *
 * 项目名称:transfer-service
 * 类名称:时间转化工具
 * 创建人:Administrator
 * 创建时间:2019年4月11日 下午3:47:53
 * 修改人:Administrator
 * 修改时间:2019年4月11日 下午3:47:53
 * 修改备注:
 * @version
 */
@SuppressWarnings("unused")
public class TimestampUtil {

    /**
     * 20位末尾的数字id
     */
    public static int Guid=100;


    public static String formatDuring(long mss) {

        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        return String.valueOf(minutes);

    }

    /**
     *
     * @Description: 生成固定长度随机字符串
     * @param:@param length
     * @param:@return
     * @return:String
     * @throws:
     * @version: v1.0.0
     * @author: Administrator
     * @date: 2021年8月4日 上午8:46:44
     */
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


    /**
     * 生成年份开头的18位纯数字字符串
     * @return
     */
    public static String getGuid() {
        Guid+=1;
        long now = System.currentTimeMillis();
        //获取4位年份数字
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy");
        //获取时间戳
        String time=dateFormat.format(now);
        String info=now+"";
        //获取三位随机数
        //int ran=(int) ((Math.random()*9+1)*100);
        //要是一段时间内的数据连过大会有重复的情况,所以做以下修改
        int ran=0;
        if(Guid>999){
            Guid=100;
        }
        ran=Guid;

        return time+info.substring(2, info.length())+ran;
    }


    /**
     *
     * @Description:验证时间戳是否超过30分钟
     * @param:@param TimeStamp
     * @param:@return
     * @param:@throws Exception
     * @return:boolean
     * @throws:
     * @version: v1.0.0
     * @author: Administrator
     * @date: 2019年7月24日 下午12:02:05
     */
    public static boolean validateTimeStamp(String TimeStamp) throws Exception{
        long timeStamp=Long.parseLong(TimeStamp);
        //    获取当前时间戳
        Long s = (System.currentTimeMillis() - timeStamp) / (1000 * 60);
        if(s>5){
            return true;
        }
        return false;
    }

    /**
     * @Description: 判断时间戳是否在一分钟内
     * @param:@param ts
     * @param:@return
     * @return:boolean
     * @throws:
     * @version: v1.0.0
     * @author: Administrator
     * @date: 2019年11月18日 上午9:36:05
     */
    private static boolean checkTimeStamp(long ts)
    {
        if (Math.abs(ts - System.currentTimeMillis() / 1000) > 60)
        {
            return false;
        }
        return true;
    }



    /**
     * 获取格式为yyyyMMddHHmmss的当前系统时间
     * @return
     */
    public static String getDate() {
        String dateName = "";
        try {
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar calendar = Calendar.getInstance();
            dateName = df.format(calendar.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateName;
    }


    /**
     * @param timeStamp  yyyyMMddHHmmss格式时间戳
     * @return java.lang.Long
     * @Description: 将时间戳转为毫秒值   yyyyMMddHHmmss
     * @Author Zangdy
     * @CreateTime 2019/4/22 11:42
     */
    public static Long timeStampToDateTime(String timeStamp) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.parse(timeStamp).getTime();
    }


    /**
     *     将13位的毫秒时间戳string类型的转化为指定时间格式的字符串
     * @param msTime
     * @param formatPattern
     * @return
     *  例如:SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     */
    public final static String parseMsStringToPatternString(String msTime, SimpleDateFormat formatPattern){
        long time = Long.parseLong(msTime);
        Date date = new Date(time);
        String parseTime = formatPattern.format(date);
        return parseTime;
    }

    /**
     * 日期字符串String(yyyy-MM-dd HH:mm:ss) 转 Date
     *
     * @param time
     * @return
     * @throws ParseException
     */
    public static Date StringToDate(String time) throws ParseException {

        Date date = new Date();
        // 注意format的格式要与日期String的格式相匹配
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = dateFormat.parse(time);
            System.out.println(date.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return date;
    }

    /**
     *
     * @Description: 时间字符串转13位时间戳
     * @param:@param time
     * @param:@return
     * @param:@throws ParseException
     * @return:String
     * @throws:
     * @version: v1.0.0
     * @author: Administrator
     * @date: 2021年7月22日 下午4:45:45
     */
    public static String StringToTimeTamp(String time){
        String result = null;
        Date date = new Date();
        // 注意format的格式要与日期String的格式相匹配
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        try {
            date = dateFormat.parse(time);
            System.out.println(date.toString());
            result = String.valueOf(date.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *Timestamp格式时间 yyyy-MM-dd HH:mm:ss格式字符串yyyy-MM-dd HH:mm:ss
     * @param time
     * @return
     */
    public static String TimestampToString(Timestamp time){
        String result = null;
        try {

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            result= dateFormat.format(time);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss.SSS
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String dateString = formatter.format(currentTime);
        return dateString;
    }


    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate2() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }


    /**
     * 获取现在时间
     *
     * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
     */
    public static Date getNowDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        ParsePosition pos = new ParsePosition(8);
        Date currentTime_2 = formatter.parse(dateString, pos);
        return currentTime_2;
    }


    /**
     * 将短时间格式字符串转换为时间 yyyy-MM-dd
     *
     * @param strDate
     * @return
     */
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     *
     * @param strDate
     * @return
     */
    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     *
     * @param strDate
     * @return
     */
    public static Date strToDateLong2(String strDate) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateTime = null;
        try {
            dateTime = simpleDateFormat.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateTime;
    }

    /**
     * Date转为String(yyyy-MM-dd HH:mm:ss)
     *
     * @param time
     * @return
     */
    public static String DateToString(Date time) {
        String dateStr = "";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss");
        try {
            dateStr = dateFormat.format(time);
            System.out.println(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateStr;
    }


    /**
     *
     * @Description:  yyyyMMddHHmmss格式转为日期
     * @param:@param time
     * @param:@return
     * @return:String
     * @throws:
     * @version: v1.0.0
     * @author: Administrator
     * @date: 2021年8月9日 上午10:35:05
     */
    public static String StringToDae(String time) {
        String datetime2 = null;
        try {
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            LocalDateTime ldt = LocalDateTime.parse(time,dtf);
            DateTimeFormatter fa = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            datetime2 = ldt.format(fa);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return datetime2;
    }

    /**
     * String(yyyy-MM-dd HH:mm:ss)转10位时间戳
     *
     * @param time
     * @return
     */
    public static Integer StringToTimestamp(String time) {

        int times = 0;
        try {
            times = (int) ((Timestamp.valueOf(time).getTime()) / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (times == 0) {
            System.out.println("String转10位时间戳失败");
        }
        return times;

    }

    /**
     *
     * @Description: 10位、13位时间戳转String 格式(2018-10-15 16:03:27) 日期
     * @param:@param timestamp
     * @param:@param simpleDateFormatType
     * @param:@return
     * @return:String
     * @throws:
     * @version: v1.0.0
     * @author: Administrator
     * @date: 2021年7月22日 下午5:15:59
     */
    public static String numberDateFormat(Object object){
        String timestamp=object.toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        String date = null;
        if (timestamp.length() == 13){
            date = sdf.format(Long.parseLong(timestamp));
        }else{
            date = sdf.format(Long.parseLong(timestamp)*1000);
        }
        return date;
    }

    /**
     *    将格式yyyy-MM-dd HH:mm:ss日期字符串转为Timestamp类型
     * @param time
     * @return
     */
    public static Timestamp stringForTimestamp(String time){
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        try {
            ts = Timestamp.valueOf(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ts;
    }

    /**
     * @Description: 10位13位时间戳转Date
     * @param timestamp 参数时间戳
     * @param simpleDateFormatType 时间戳类型("yyyy-MM-dd HH:mm:ss")
     * @return
     */
    public static Date numberDateFormatToDate(String timestamp,String  simpleDateFormatType){
        SimpleDateFormat sdf = new SimpleDateFormat(simpleDateFormatType);//要转换的时间格式
        Date date = null;
        try {
            if (timestamp.length() == 13){
                date = sdf.parse(sdf.format(Long.parseLong(timestamp)));
            }else{
                date = sdf.parse(sdf.format(Long.parseLong(timestamp)*1000));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 10位int型的时间戳转换为String(yyyy-MM-dd HH:mm:ss)
     *
     * @param time
     * @return
     */
    public static String timestampToString(Integer time) {
        // int转long时,先进行转型再进行计算,否则会是计算结束后在转型
        long temp = (long) time * 1000;
        Timestamp ts = new Timestamp(temp);
        String tsStr = "";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 方法一
            tsStr = dateFormat.format(ts);
            System.out.println(tsStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tsStr;
    }

    /**
     * 10位时间戳转Date
     *
     * @param time
     * @return
     */
    public static Date TimestampToDate(Integer time) {
        long temp = (long) time * 1000;
        Timestamp ts = new Timestamp(temp);
        Date date = new Date();
        try {
            date = ts;
            // System.out.println(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * Date类型转换为10位时间戳
     *
     * @param time
     * @return
     */
    public static Integer DateToTimestamp(Date time) {
        Timestamp ts = new Timestamp(time.getTime());

        return (int) ((ts.getTime()) / 1000);
    }


    /**
     * 获取系统当前时间,格式为yyyy-MM-dd HH:mm:ss.SSS
     * @return
     */
    public static Timestamp getNowTimestamp() {
        Date date = new Date();
        Timestamp nousedate = new Timestamp(date.getTime());

        return nousedate;
    }


    /**
     * 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式,返回字符型的分钟
     */
    public static String getTwoHour(String st1, String st2) {
        String[] kk = null;
        String[] jj = null;
        kk = st1.split(":");
        jj = st2.split(":");
        if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0])) {
            return "0";
        }else {
            double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;
            double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;
            if ((y - u) > 0)
                return y - u + "";
            else
                return "0";
        }
    }

    /**
     * 得到二个日期间的间隔天数
     */
    public static String getTwoDay(String sj1, String sj2) {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        long day = 0;
        try {
            java.util.Date date = myFormatter.parse(sj1);
            java.util.Date mydate = myFormatter.parse(sj2);
            day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (Exception e) {
            return "";
        }
        return day + "";
    }

    /**
     * 时间前推或后推分钟,其中JJ表示分钟.
     */
    public static String getPreTime(String sj1, String jj) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String mydate1 = "";
        try {
            Date date1 = format.parse(sj1);
            long Time = (date1.getTime() / 1000) + Integer.parseInt(jj) * 60;
            date1.setTime(Time * 1000);
            mydate1 = format.format(date1);
        } catch (Exception e) {
        }
        return mydate1;
    }

    /**
     * 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
     */
    public static String getNextDay(String nowdate, String delay) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String mdate = "";
            Date d = strToDate(nowdate);
            long myTime = (d.getTime() / 1000) + Integer.parseInt(delay) * 24 * 60 * 60;
            d.setTime(myTime * 1000);
            mdate = format.format(d);
            return mdate;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 判断二个时间是否在同一个周
     *
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameWeekDates(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(date1);
        cal2.setTime(date2);
        int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
        if (0 == subYear) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        } else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
            // 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        } else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        }
        return false;
    }

    /**
     * 产生周序列,即得到当前时间所在的年度是第几周
     *
     * @return
     */
    public static String getSeqWeek() {
        Calendar c = Calendar.getInstance(Locale.CHINA);
        String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
        if (week.length() == 1)
            week = "0" + week;
        String year = Integer.toString(c.get(Calendar.YEAR));
        return year + week;
    }

    /**
     * 获得一个日期所在的周的星期几的日期,如要找出2002年2月3日所在周的星期一是几号
     *
     * @param sdate
     * @param num
     * @return
     */
    public static String getWeek(String sdate, String num) {
        // 再转换为时间
        Date dd = TimestampUtil.strToDate(sdate);
        Calendar c = Calendar.getInstance();
        c.setTime(dd);
        if (num.equals("1")) // 返回星期一所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        else if (num.equals("2")) // 返回星期二所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
        else if (num.equals("3")) // 返回星期三所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
        else if (num.equals("4")) // 返回星期四所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
        else if (num.equals("5")) // 返回星期五所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        else if (num.equals("6")) // 返回星期六所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        else if (num.equals("0")) // 返回星期日所在的日期
            c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
    }

    /**
     * 根据一个日期,返回是星期几的字符串
     *
     * @param sdate
     * @return
     */
    public static String getWeek(String sdate) {
        // 再转换为时间
        Date date = TimestampUtil.strToDate(sdate);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // int hour=c.get(Calendar.DAY_OF_WEEK);
        // hour中存的就是星期几了,其范围 1~7
        // 1=星期日 7=星期六,其他类推
        return new SimpleDateFormat("EEEE").format(c.getTime());
    }

    public static String getWeekStr(String sdate) {
        String str = "";
        str = TimestampUtil.getWeek(sdate);
        if ("1".equals(str)) {
            str = "星期日";
        } else if ("2".equals(str)) {
            str = "星期一";
        } else if ("3".equals(str)) {
            str = "星期二";
        } else if ("4".equals(str)) {
            str = "星期三";
        } else if ("5".equals(str)) {
            str = "星期四";
        } else if ("6".equals(str)) {
            str = "星期五";
        } else if ("7".equals(str)) {
            str = "星期六";
        }
        return str;
    }

    /**
     * 两个时间之间的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static long getDays(String date1, String date2) {
        if (date1 == null || date1.equals(""))
            return 0;
        if (date2 == null || date2.equals(""))
            return 0;
        // 转换为标准时间
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date = null;
        java.util.Date mydate = null;
        try {
            date = myFormatter.parse(date1);
            mydate = myFormatter.parse(date2);
        } catch (Exception e) {
        }
        long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }

    /**
     * 形成如下的日历 , 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间
     * 此函数返回该日历第一行星期日所在的日期
     *
     * @param sdate
     * @return
     */
    public static String getNowMonth(String sdate) {
        // 取该时间所在月的一号
        sdate = sdate.substring(0, 8) + "01";

        // 得到这个月的1号是星期几
        Date date = TimestampUtil.strToDate(sdate);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int u = c.get(Calendar.DAY_OF_WEEK);
        String newday = TimestampUtil.getNextDay(sdate, (1 - u) + "");
        return newday;
    }


    /**
     *
     * @Description: string 转date
     * @param:@param sdate
     * @param:@return
     * @return:Date
     * @throws:
     * @version: v1.0.0
     * @author: Administrator
     * @date: 2019年12月26日 上午11:38:12
     */
    public static Date getDateShort(String sdate) throws Exception{
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        date = sdf.parse(sdate);
        return date;
    }

    /**
     *
     * @Description: 将字符串转为13位时间戳
     * @param:@param time
     * @param:@return
     * @return:long
     * @throws:
     * @version: v1.0.0
     * @author: Administrator
     * @date: 2021年7月13日 上午9:20:41
     */
    public static long getStringToDate(String time) {
        SimpleDateFormat sf  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        try{
            date = sf.parse(time);
        } catch(ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();
    }


    /**
     *     将20210916114656格式时间转化为 yyyy-MM-dd HH:mm:ss
     *
     * @param strDate
     * @return
     */
    public static String intToDateStr(String strDate) {
        SimpleDateFormat formatter1 = null;
        SimpleDateFormat formatter2 = null;
        Date time1=null;
        String time2=null;
        try {
            formatter2=new SimpleDateFormat("yyyyHHddHHmmss");
            time1=formatter2.parse(strDate);
            formatter1=new SimpleDateFormat("yyyy-HH-dd HH:mm:ss");
            time2=formatter1.format(time1);
        } catch (Exception e) {
            return strDate;
        }
        return time2;
    }

}
复制代码

 

posted @   小妖兔Q  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示