Java使用什么函数可以获得现在的系统时间,要求以年月日分开展示
时间: 2024-03-08 18:50:29 浏览: 10
Java中可以使用`java.time.LocalDate`类获取当前的系统日期,以年月日的形式展示。示例代码如下:
```java
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 输出当前日期,格式为:yyyy年MM月dd日
System.out.printf("%d年%d月%d日",
currentDate.getYear(),
currentDate.getMonthValue(),
currentDate.getDayOfMonth());
}
}
```
输出结果为:`2021年10月29日`。
相关问题
用Java语句编写一个函数实现按照年月日时分秒打印当前时间
可以使用Java中的DateFormat类和Date类来实现按照年月日时分秒打印当前时间的功能,具体代码如下:
```java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PrintCurrentTime {
public static void main(String[] args) {
String pattern = "yyyy-MM-dd HH:mm:ss";
DateFormat df = new SimpleDateFormat(pattern);
String currentTime = df.format(new Date());
System.out.println(currentTime);
}
}
```
其中,DateFormat类用于格式化日期,SimpleDateFormat是DateFormat的一个实现类,可以通过指定的模式将日期格式化为字符串。Date类则表示当前时间,使用new Date()获取当前时间对象,然后将它传递给SimpleDateFormat的format方法,即可得到按照指定格式格式化后的时间字符串。最后,使用System.out.println方法将该字符串打印出来即可。
js时间转化函数年月日
JavaScript中有一个内置的日期对象Date,可以用来处理日期和时间。要转换时间为年、月、日的形式,可以使用Date对象提供的getYear()、getMonth()、getDay()方法。
其中getYear()方法返回的是距离1900年的年份差。因此,需要加上1900年才是实际的年份。getMonth()方法返回的是0-11,所以需要加1后才是实际的月份。getDay()方法返回的是一周中的第几天,0为周日。
例如,要将时间戳转换为年月日的形式,可以按照以下方式编写函数:
function timestampToDate(timestamp) {
const date = new Date(timestamp * 1000);
const year = date.getYear() + 1900;
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}年${month}月${day}日`;
}
其中,将时间戳乘以1000的原因是因为JavaScript中的时间戳是以秒为单位的,而Date对象传入的是以毫秒为单位的值。
使用以上函数,传入时间戳,即可返回对应的年月日字符串。