如何用Java獲取當前時間戳?

banq發表於2022-09-18

在本教程中,我們將學習如何以各種方式在 java 中獲取當前時間戳。
讓我們跳入JDK 8 和更早版本 jdk的正確示例。

import java.sql.Timestamp;

public class CurrentTimestampExample1 {

    public static void main(String[] args) {

        long timestampInMillies = System.currentTimeMillis();
        
        Timestamp timestamp = new Timestamp(timestampInMillies);
        System.out.println("timestamp now : "+timestamp);
    }

}


其他六種方式:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentTimestampExample7 {

    public static void main(String[] args) {

        LocalDateTime localDateTime = LocalDateTime.now();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS");

        String timestamp = formatter.format(localDateTime);

        System.out.println("timestamp now : " + timestamp);
    }
}

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class CurrentTimestampExample6 {

    public static void main(String[] args) {

        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime localDateTime = ZonedDateTime.now(zoneId);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS");

        String timestamp = formatter.format(localDateTime);

        System.out.println("timestamp now : " + timestamp);
    }
}

import java.time.Instant;

public class CurrentTimestampExample5 {

    public static void main(String[] args) {

        Instant instant = Instant.now();

        System.out.println("timestamp now : " + instant);
    }

}

import java.sql.Timestamp;
import java.time.Instant;

public class CurrentTimestampExample4 {

    public static void main(String[] args) {

        long timeInMillis = System.currentTimeMillis();

        Timestamp timestamp = new Timestamp(timeInMillis);

        Instant instant = timestamp.toInstant();

        System.out.println("timestamp now : " + instant);
    }
}
import java.text.SimpleDateFormat;
import java.util.Date;

public class CurrentTimestampExample2 {

    public static void main(String[] args) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateNow = new Date();

        String timestampNow = simpleDateFormat.format(dateNow);

        System.out.println("timestamp now : " + timestampNow);
    }

}
import java.time.Instant;
import java.util.Date;

public class CurrentTimestampExample2 {

    public static void main(String[] args) {

        Date dateNow = new Date();

        Instant instant = dateNow.toInstant();

        System.out.println("timestamp now : " + instant);
    }
}




 

相關文章