Java获取当前时间戳/时间戳转换

时间戳精度有两个概念:1是精确到秒,2是精确到毫秒。

要操作时间戳和时间戳转换为时间一般对应的对象就是Date,而Date各种转换离不开SimpleDateFormat;

如果是要获取时间指定的年月日时,一般对应的是LocalDate,而LocalDate各种转换离不开DateFormatter;

package com.jsoft.testjavabasics.test1;

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

/**
 * Hello world!
 * @author jim
 * @date 2017/11/25
 */
public class App {
    public static void main(String[] args) {
        // 精确到毫秒
        // 获取当前时间戳
        System.out.println(System.currentTimeMillis());
        System.out.println(Calendar.getInstance().getTimeInMillis());
        System.out.println(new Date().getTime());

        // 精确到秒
        // 获取当前时间戳
        System.out.println(System.currentTimeMillis() / 1000);
        System.out.println(Calendar.getInstance().getTimeInMillis() / 1000);
        System.out.println(new Date().getTime() / 1000);

        // 精确到毫秒
        // 获取指定格式的时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        // 输出字符串
        System.out.println(df.format(new Date()));
        // 获取指定时间Date对象,参数是时间戳,只能精确到秒
        System.out.println(new Date(1510369871));
        df.getCalendar();
        // 获取指定时间的时间戳
        try {
            System.out.println(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS").parse("2017/11/11 11:11:11:111").getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

示例工程:https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test29/test1

参考:

http://tool.chinaz.com/Tools/unixtime.aspx(时间戳测试工具)

https://www.cnblogs.com/chen-lhx/p/5915113.html

http://blog.csdn.net/zhangzehai2234/article/details/53365633

https://www.cnblogs.com/zhujiabin/p/6168671.html?utm_source=itdadao&utm_medium=referral

http://blog.csdn.net/wanglj7525/article/details/43408749

猜你喜欢

转载自blog.csdn.net/rocling/article/details/81814410
今日推荐