java获取时间字符串
时间: 2024-01-23 14:13:41 浏览: 33
以下是两种Java获取时间字符串的例子:
1.获取当前时间戳的前10位字符串
```java
long l = System.currentTimeMillis();String s = (l + "").substring(0, 10);
System.out.println(s); // 输出:1619023456
```
2.获取当前时间的字符串表示
```java
import java.text.SimpleDateFormat;
import java.util.Date;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String now = sdf.format(new Date());
System.out.println(now); // 输出:2021-04-21 16:44:16
```
相关问题
java获取时间做字符串
在Java中,可以使用`SimpleDateFormat`类来将时间格式化成字符串。下面是一个简单的代码示例:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 获取当前时间
Date now = new Date();
// 创建日期格式化对象,指定格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将日期格式化成字符串
String formattedDate = sdf.format(now);
// 打印结果
System.out.println(formattedDate);
}
}
```
在上述示例中,首先获取当前时间对象`now`。然后,创建一个`SimpleDateFormat`对象来指定日期格式,这里使用的是`yyyy-MM-dd HH:mm:ss`,表示年份-月份-日期 小时:分钟:秒钟的格式。接下来,调用`format()`方法将时间对象格式化成字符串。最后,将格式化后的字符串打印出来。
运行上述代码,输出的结果示例为:`2021-10-10 12:34:56`。你可以根据需要自定义日期格式,并根据具体要求获取相应的时间字符串。
java 获取当前时间字符串
可以使用 SimpleDateFormat 类来获取当前时间的字符串表示。示例代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String strDate = formatter.format(date);
System.out.println(strDate);
}
}
```
输出结果为当前时间的字符串表示,例如:2021-08-31 14:30:00。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)