如何用Java获取当前时间戳?

22-09-18 banq

在本教程中,我们将学习如何以各种方式在 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);
    }
}