java如何获取当前日期和时间

本文详细介绍Java中获取当前时间的各种方法,包括使用System.currentTimeMillis(), java.util.Date, Calendar, 以及Java 8新引入的Date/Time API如LocalDate, LocalTime和LocalDateTime等。
该文章已生成可运行项目,

本篇博客主要总结java里面关于获取当前时间的一些方法

System.currentTimeMillis()

获取标准时间可以通过System.currentTimeMillis()方法获取,此方法不受时区影响,得到的结果是时间戳格式的。例如:

1543105352845  

我们可以将时间戳转化成我们易于理解的格式

SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
System.out.println(formatter.format(date));

则该时间戳对应的时间为:

2018-11-25 at 01:22:12 CET

值得注意的是,此方法会根据我们的系统时间返回当前值,因为世界各地的时区是不一样的。

java.util.Date

在Java中,获取当前日期最简单的方法之一就是直接实例化位于Java包java.util的Date类。

Date date = new Date(); // this object contains the current date value 

上面获取到的日期也可以被format成我们需要的格式,例如:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");  
System.out.println(formatter.format(date));  

Calendar API

Calendar类,专门用于转换特定时刻和日历字段之间的日期和时间。

使用Calendar 获取当前日期和时间非常简单:

Calendar calendar = Calendar.getInstance(); // get current instance of the calendar  

与date一样,我们也可以非常轻松地format这个日期成我们需要的格式

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");  
System.out.println(formatter.format(calendar.getTime()));  

上面代码打印的结果如下:

25-11-2018 00:43:39

Date/Time API

Java 8提供了一个全新的API,用以替换java.util.Date和java.util.Calendar。Date / Time API提供了多个类,帮助我们来完成工作,包括:

  • LocalDate
  • LocalTime
  • LocalDateTime
  • ZonedDateTime

LocalDate

LocalDate只是一个日期,没有时间。 这意味着我们只能获得当前日期,但没有一天的具体时间。

LocalDate date = LocalDate.now(); // get the current date 

我们可以format它

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");  
System.out.println(date.format(formatter));  

得到的结果只有年月日,例如:

25-11-2018 

LocalTime

LocalTime与LocalDate相反,它只代表一个时间,没有日期。 这意味着我们只能获得当天的当前时间,而不是实际日期:

LocalTime time = LocalTime.now(); // get the current time  

可以按如下方式format

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");  
System.out.println(time.format(formatter)); 

得到的结果类似如下:

00:55:58  

LocalDateTime

最后一个是LocalDateTime,也是Java中最常用的Date / Time类,代表前两个类的组合 - 即日期和时间的值:

LocalDateTime dateTime = LocalDateTime.now(); // get the current date and time  

format的方式也一样

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");  
System.out.println(dateTime.format(formatter));  

得到的日期结果类似于:

25-11-2018 00:57:20  

 

本文章已经生成可运行项目
<think>我们正在讨论Java中分别获取当前日期当前时间的方法。根据引用,我们有几种不同的方式: 1. 使用传统的Date类(如引用[1]所示)可以获取当前日期时间,但如果我们想分别获取日期部分时间部分,需要结合其他类。 2. 使用Java 8引入的java.time包中的类(如引用[2]中使用的LocalDate)可以方便地分别处理日期时间。 根据用户的需求,分别获取当前日期当前时间,我们可以使用以下两种方式: a) 使用DateCalendar(旧API,适用于Java 7及之前) b) 使用java.time包(新API,Java 8及以上) 由于用户要求分别获取日期时间,我们分别提供两种方法。 方法一:使用旧API(DateCalendar) 获取当前日期:我们可以通过设置时间为0:00:00来忽略时间部分,但这样并不是真正的“日期”。更合适的是使用Calendar来提取日期的年、月、日部分。 或者,我们可以使用SimpleDateFormat来格式化日期,只保留日期部分。 获取当前时间:同样,我们可以格式化只保留时间部分。 方法二:使用新API(java.time包) 获取当前日期:使用LocalDate类(只包含日期获取当前时间:使用LocalTime类(只包含时间) 下面分别给出代码示例。 注意:引用[2]中提到了使用LocalDate获取日期并减去一个月,我们可以借鉴其获取当前日期的方法。引用[3]提到了Calendar类可以操作日期,我们可以用它来获取日期时间。 我们将分为两部分:旧API新API。 一、旧API(Java 7及之前) 1. 获取当前日期(格式化为字符串,仅包含日期) 2. 获取当前时间(格式化为字符串,仅包含时间) 或者,我们可以通过Calendar获取各个字段,但直接格式化成字符串更直观。 二、新API(Java 8及以上) 1. 获取当前日期:LocalDate.now() 2. 获取当前时间:LocalTime.now() 代码示例: 旧API示例: ```java import java.text.SimpleDateFormat; import java.util.Date; public class OldDateTimeExample { public static void main(String[] args) { // 创建一个Date对象表示当前时间 Date now = new Date(); // 格式化日期部分 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String currentDate = dateFormat.format(now); // 格式化时间部分 SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); String currentTime = timeFormat.format(now); System.out.println("当前日期: " + currentDate); System.out.println("当前时间: " + currentTime); } } ``` 新API示例: ```java import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class NewDateTimeExample { public static void main(String[] args) { // 获取当前日期 LocalDate currentDate = LocalDate.now(); // 获取当前时间 LocalTime currentTime = LocalTime.now(); // 定义日期格式化器(可选,默认格式为ISO_LOCAL_DATE,即yyyy-MM-dd) DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 定义时间格式化器(可选,默认格式为ISO_LOCAL_TIME,如HH:mm:ss.nnn) DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); // 格式化输出(如果不需要特定格式,可以直接调用toString(),但格式可能会包含毫秒等) System.out.println("当前日期: " + currentDate.format(dateFormatter)); System.out.println("当前时间: " + currentTime.format(timeFormatter)); } } ``` 注意:在旧API中,我们使用SimpleDateFormat来格式化日期时间,而在新API中,我们使用DateTimeFormatter。 另外,新API中,LocalDateLocalTime分别只包含日期时间的部分,所以直接使用它们就可以分别得到日期时间,无需格式化(格式化只是为了输出为字符串,如果不需要字符串,可以直接使用对象)。 我们还可以使用Calendar类来分别获取日期时间(旧API),但代码较为繁琐,不如格式化简单。例如: ```java import java.util.Calendar; public class CalendarExample { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始,需要+1 int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); System.out.println("当前日期: " + year + "-" + month + "-" + day); System.out.println("当前时间: " + hour + ":" + minute + ":" + second); } } ``` 但是,这种方法需要手动拼接字符串,而且要注意月份需要加1,且格式可能不够美观(比如个位数月份前面没有0)。 因此,通常我们会选择使用SimpleDateFormat来格式化日期时间。 总结: 推荐使用Java 8的新日期时间API(java.time包),因为它更清晰、更易用,并且线程安全。如果使用旧版本的Java,则使用DateSimpleDateFormat(注意SimpleDateFormat不是线程安全的)或Calendar。 根据引用[3],Calendar类也可以用于日期时间的操作,但是新API是更好的选择。 最后,生成相关问题。 </think>### Java中分别获取当前日期当前时间的方法 在Java获取当前日期时间有新旧两种API,下面分别介绍实现方法: #### 1. **Java 8+ 新日期时间API(推荐)** Java 8引入了`java.time`包,提供了更简洁、线程安全的日期时间处理方式。 ```java import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class DateTimeExample { public static void main(String[] args) { // 获取当前日期 LocalDate currentDate = LocalDate.now(); System.out.println("当前日期: " + currentDate); // 默认格式: yyyy-MM-dd // 获取当前时间 LocalTime currentTime = LocalTime.now(); System.out.println("当前时间: " + currentTime); // 默认格式: HH:mm:ss.nnn // 自定义格式化 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日"); DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH时mm分ss秒"); System.out.println("格式化日期: " + currentDate.format(dateFormatter)); System.out.println("格式化时间: " + currentTime.format(timeFormatter)); } } ``` **输出示例**: ``` 当前日期: 2023-10-05 当前时间: 15:30:45.123 格式化日期: 2023年10月05日 格式化时间: 15时30分45秒 ``` #### 2. **旧版API(Java 7及之前)** 使用`java.util.Date``SimpleDateFormat`(注意:非线程安全)。 ```java import java.text.SimpleDateFormat; import java.util.Date; public class LegacyDateTime { public static void main(String[] args) { // 获取当前完整日期时间 Date now = new Date(); // 提取日期部分 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String currentDate = dateFormat.format(now); // 提取时间部分 SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); String currentTime = timeFormat.format(now); System.out.println("当前日期: " + currentDate); System.out.println("当前时间: " + currentTime); } } ``` #### 3. **使用Calendar类(过渡方案)** 适用于需要日期计算的场景[^3]。 ```java import java.util.Calendar; import java.text.SimpleDateFormat; public class CalendarExample { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); // 获取日期部分 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String datePart = dateFormat.format(calendar.getTime()); // 获取时间部分 SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); String timePart = timeFormat.format(calendar.getTime()); System.out.println("日期: " + datePart); System.out.println("时间: " + timePart); } } ``` ### 关键区别 | **特性** | `java.time` API (Java 8+) | 旧版API | |------------------|---------------------------|---------------------| | 线程安全 | ✅ 是 | ❌ `SimpleDateFormat`非线程安全 | | 日期时间分离 | ✅ `LocalDate`/`LocalTime`| ❌ 需要手动格式化分离 | | 时区处理 | ✅ 明确(`ZonedDateTime`)| ❌ 隐式依赖系统时区 | | 月份表示 | ✅ 1-12(符合常识) | ❌ 0-11(需+1调整) | | 推荐指数 | ⭐⭐⭐⭐⭐ | ⭐⭐ | > 💡 **最佳实践**: > - 优先使用Java 8+的`java.time` API > - 需要兼容旧系统时再考虑`SimpleDateFormat`(确保线程安全) > - 格式化符号说明:`yyyy`=年,`MM`=月,`dd`=日,`HH`=时(24h),`mm`=分,`ss`=秒
评论 17
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值