当前位置:首页 > Java

java中如何获取当前时间

2026-01-15 17:28:35Java

获取当前时间的几种方法

使用 java.time 包(Java 8及以上推荐)

import java.time.LocalDateTime;
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间: " + currentTime);

使用 System.currentTimeMillis()

long currentTimeMillis = System.currentTimeMillis();
System.out.println("当前时间戳(毫秒): " + currentTimeMillis);

使用 java.util.Date

import java.util.Date;
Date currentDate = new Date();
System.out.println("当前时间: " + currentDate);

使用 java.util.Calendar

import java.util.Calendar;
Calendar calendar = Calendar.getInstance();
System.out.println("当前时间: " + calendar.getTime());

格式化输出时间

import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTime = LocalDateTime.now().format(formatter);
System.out.println("格式化时间: " + formattedTime);

获取特定时区的时间

import java.time.ZoneId;
import java.time.ZonedDateTime;
ZonedDateTime zonedTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println("上海时区时间: " + zonedTime);

获取当前时间的各个部分

LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
System.out.printf("%d年%d月%d日 %d时%d分%n", year, month, day, hour, minute);

注意事项

  • java.time 包是Java 8引入的现代日期时间API,推荐使用
  • DateCalendar 是旧API,存在线程安全等问题
  • 时间格式化可以使用 DateTimeFormatter
  • 处理时区时建议明确指定,避免依赖系统默认时区

java中如何获取当前时间

java中如何获取当前时间

标签: 时间java
分享给朋友:

相关文章

如何查看java版本

如何查看java版本

查看 Java 版本的方法 通过命令行工具 打开终端(Windows 为命令提示符或 PowerShell,macOS/Linux 为 Terminal),输入以下命令并回车: java -v…

java如何创建文件

java如何创建文件

使用 File 类创建文件 通过 File 类的 createNewFile() 方法创建文件。此方法返回布尔值,表示文件是否成功创建。 import java.io.File; import ja…

java如何创建线程

java如何创建线程

创建线程的方法 在Java中,创建线程主要有两种方式:继承Thread类和实现Runnable接口。以下是具体实现方法: 继承Thread类 通过继承Thread类并重写run()方法可以创建线程…

java如何运行

java如何运行

运行Java程序的基本方法 Java程序的运行需要经过编写、编译和执行三个主要阶段。以下是具体步骤: 编写Java源代码 创建一个以.java为后缀的文件,例如HelloWorld.java。文件内…

java如何输入

java如何输入

使用Scanner类进行输入 Scanner类是Java中最常用的输入工具,适用于从控制台或文件读取数据。需要导入java.util.Scanner包。 基本语法: Scanner s…

如何安装java

如何安装java

下载Java开发工具包(JDK) 访问Oracle官方网站或OpenJDK下载页面,选择适合操作系统的版本(Windows、macOS或Linux)。推荐下载最新的长期支持(LTS)版本,如Java…