java代码格式化时间戳
时间: 2023-12-02 18:04:24 浏览: 36
你可以使用`java.util.Date`类和`java.text.SimpleDateFormat`类来格式化时间戳。以下是一个示例代码:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class TimestampFormatter {
public static void main(String[] args) {
long timestamp = System.currentTimeMillis(); // 获取当前时间戳
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(new Date(timestamp));
System.out.println("Formatted Date: " + formattedDate);
}
}
```
上述代码将获取当前时间戳并将其格式化为"yyyy-MM-dd HH:mm:ss"的字符串表示形式。你可以根据需要修改日期时间格式。
相关问题
Java 时间戳怎么格式化日期
在Java中,可以使用SimpleDateFormat类将时间戳格式化为日期。以下是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimestampToDate {
public static void main(String[] args) {
long timestamp = System.currentTimeMillis(); // 获取当前时间戳
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置日期格式
String date = sdf.format(new Date(timestamp)); // 格式化时间戳为日期字符串
System.out.println(date); // 输出格式化后的日期字符串
}
}
```
在上面的示例中,我们使用`SimpleDateFormat`类设置日期格式为`"yyyy-MM-dd HH:mm:ss"`,然后将时间戳格式化为日期字符串。最后,我们将格式化后的日期字符串输出到控制台。
java 时间戳转格式化时间
可以使用 SimpleDateFormat 类将时间戳转换为格式化时间。具体代码如下:
long timestamp = System.currentTimeMillis(); // 获取当前时间戳
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedTime = sdf.format(new Date(timestamp));
System.out.println(formattedTime);
输出结果类似于:2022-01-01 12:00:00。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)