首页 > 技术文章 > 时间戳、String、Date转换

siyyawu 2019-05-07 20:39 原文

时间戳(String or long) =》Date

long s=1557230621043L;
Date date=new Date(s);
System.out.println(date);

Date转时间戳

getTime()

 

string.date相互转换

//string转date
    public static void stringToDate(){
        try{
            String str="2016-10-24 21:59:06";
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(sdf.parse(str));
            System.out.println(sdf.parse(str).getTime());
        }catch(Exception e){
            e.printStackTrace();
        }    
    }
    
    //date转string1
    public static void dateToString1(){
        try {
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            System.out.println(format.format(new Date().getTime()));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    
    //date转string2
    public static void dateToString2(){
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            Calendar cal=Calendar.getInstance();
            System.out.println(format.format(cal.getTime()));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

系统微秒

System.currentTimeMillis();

纳秒

System.nanoTime();

推荐阅读