Java教程

Java日期和时间戳互转(看这一篇就够了)

本文主要是介绍Java日期和时间戳互转(看这一篇就够了),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java日期和时间戳互转(看这一篇就够了)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class IOTestMain {
    public static void main(String[] args) throws ParseException {
        System.out.println(System.currentTimeMillis());
        System.out.println(date2long("2021", "09", "29", "14", "55", "03"));
        System.out.println(long2date(date2long("2021", "09", "29", "14", "55", "03")));
    }

    public static long date2long(String year, String month, String day, String hour, String minutes, String sec) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(year);
        stringBuilder.append("/");
        stringBuilder.append(month);
        stringBuilder.append("/");
        stringBuilder.append(day);
        stringBuilder.append(" ");
        stringBuilder.append(hour);
        stringBuilder.append(":");
        stringBuilder.append(minutes);
        stringBuilder.append(":");
        stringBuilder.append(sec);

        String sDt = stringBuilder.toString();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date dt = null;
        try {
            dt = sdf.parse(sDt);
            if (dt != null) {
                return dt.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1L;
    }

    public static String long2date(long timestamp) throws ParseException {
        Date date = new Date();
        date.setTime(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
}

输出:

1632972081606
1632898503000
2021-09-29 14:55:03

Process finished with exit code 0
这篇关于Java日期和时间戳互转(看这一篇就够了)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!