在Java中使用java.util.Date类和java.time.LocalDate类来获取系统当前的时间,年份,月份和日期。
一、使用java.util.Date类获得当前日期
java.util.Date类表示特定的瞬间,精确到毫秒。下面是获取当前日期和时间的代码示例:
import java.util.Date;
public class GetCurrentDateTime {
public static void main(String[] args) {
// create a date object with the current date and time.
Date date = new Date();
// print the date
System.out.println("当前日期和时间: " + date.toString());
}
}
二、使用java.time.LocalDate获取当前年月日
使用Java 8引入的java.time包中的LocalDate类,可以很方便地获取当前日期的年份,月份和日子。以下是操作的具体代码:
import java.time.LocalDate;
public class GetCurrentDate {
public static void main(String[] args) {
// get the current date
LocalDate currentDate = LocalDate.now();
// get the year
int year = currentDate.getYear();
// get the month
int month = currentDate.getMonthValue();
// get the day
int day = currentDate.getDayOfMonth();
// print the current date
System.out.println("当前年份: " + year);
System.out.println("当前月份: " + month);
System.out.println("当前日期: " + day);
}
}
三、使用java.text.SimpleDateFormat格式化日期
java.text.SimpleDateFormat是一个可以以用户定义的模式格式化 Date 对象的具体类。
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormatCurrentDateTime {
public static void main(String[] args) {
// create a date object with the current date and time.
Date now = new Date();
// create an instance of SimpleDateFormat
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// format the date
String currentDateAndTime = formatter.format(now);
// print the date and time
System.out.println("当前年月日和时间: " + currentDateAndTime);
}
}
织梦狗教程
本文标题为:Java获取系统当前时间年月日
基础教程推荐
猜你喜欢
- 用java实现扫雷游戏 2022-12-06
- 一文了解Java 线程池的正确使用姿势 2023-06-17
- JVM分析之类加载机制详解 2023-04-06
- Java去掉小数点后面无效0的方案与建议 2023-02-18
- Project Reactor源码解析publishOn使用示例 2023-04-12
- Java File类的概述及常用方法使用详解 2023-05-18
- 工厂方法在Spring框架中的运用 2023-06-23
- SpringBoot配置文件中密码属性加密的实现 2023-03-11
- Java使用EasyExcel进行单元格合并的问题详解 2023-01-18
- 全局记录Feign的请求和响应日志方式 2023-01-09