get time stamp java

ht‮:spt‬//www.lautturi.com
get time stamp java

To get a timestamp in Java, you can use the System.currentTimeMillis() method, which returns the current time in milliseconds since the epoch (midnight, January 1, 1970). Here's an example of how you could use this method to get the current timestamp:

long timestamp = System.currentTimeMillis();
System.out.println("Timestamp: " + timestamp);

This code will output the current timestamp in milliseconds, for example "1616658896227".

Alternatively, you can use the Instant class from the Java 8 Date and Time API to get the current timestamp. Here's an example of how you could do this:

import java.time.Instant;

Instant timestamp = Instant.now();
System.out.println("Timestamp: " + timestamp);

This code will output the current timestamp in the ISO-8601 format, for example "2022-12-20T16:34:05.227Z".

To format the timestamp in a different way, such as in the format "YYYY-MM-DD HH:mm:ss", you can use the DateTimeFormatter class from the Java 8 Date and Time API. Here's an example of how you could do this:

import java.time.Instant;
import java.time.format.DateTimeFormatter;

Instant timestamp = Instant.now();
String formattedTimestamp = timestamp.atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("Timestamp: " + formattedTimestamp);

This code will output the current timestamp in the format "YYYY-MM-DD HH:mm:ss", for example "2022-12-20 16:34:05".

Created Time:2017-11-01 12:04:59  Author:lautturi