用java生成一个时间戳的代码包含yyyy-mm-dd
时间: 2023-04-03 14:01:05 浏览: 57
下面是用 Java 生成时间戳的代码,包含 yyyy-mm-dd 格式:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimestampGenerator {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String timestamp = sdf.format(new Date());
System.out.println(timestamp);
}
}
```
这段代码会生成当前时间的时间戳,并以 yyyy-mm-dd 的格式输出。希望对你有帮助!
相关问题
将以下代码生成的时间戳换算成yyyy-MM-dd HH-mm-ss形式的 LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai")); long time = ldt.toEpochSecond(ZoneOffset.ofHours(8));
可以使用以下代码将时间戳转换为yyyy-MM-dd HH-mm-ss格式:
```
long timestamp = time * 1000; // 将时间戳转换为毫秒级别
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = Instant.ofEpochMilli(timestamp)
.atZone(ZoneId.of("Asia/Shanghai"))
.format(formatter);
System.out.println(formattedDateTime); // 输出格式化后的时间
```
其中,将时间戳转换为毫秒级别是因为Java中的时间戳表示的是以秒为单位的时间戳,而我们需要的是以毫秒为单位的时间戳。然后,使用DateTimeFormatter指定输出的时间格式,并使用Instant和ZoneId将时间戳转换为LocalDateTime对象。最后,使用format方法将LocalDateTime对象格式化为字符串形式。
DateTimeFormatter生成时间戳
您可以使用`DateTimeFormatter`类来生成时间戳。下面是一个示例代码:
```java
import java.time.Instant;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String timestamp = formatter.format(instant);
System.out.println("Timestamp: " + timestamp);
}
}
```
这段代码将使用`DateTimeFormatter`将当前时间戳格式化为"yyyy-MM-dd HH:mm:ss.SSS"的字符串格式。您可以根据需要选择不同的时间戳格式,具体的格式化模式可以参考Java官方文档中关于`DateTimeFormatter`类的说明。