900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > java 获取当前日期时间_如何使用Java获取当前日期和时间

java 获取当前日期时间_如何使用Java获取当前日期和时间

时间:2024-03-06 01:47:50

相关推荐

java 获取当前日期时间_如何使用Java获取当前日期和时间

java 获取当前日期时间

Java provides two classes to get current date and time – Date and Calendar.

Java提供了两个类来获取当前日期和时间-Date和Calendar 。

用Java获取当前日期 (Get Current Date in Java)

Here is the simple program showing how we can use these classes to get the current date and time in Java.

这是一个简单的程序,显示了我们如何使用这些类来获取Java中的当前日期和时间。

package com.journaldev.util;import java.util.Calendar;import java.util.Date;public class DateAndTimeUtil {public static void main(String[] args) {//Get current date using DateDate date = new Date();System.out.println("Current date using Date = "+date.toString());//Get current date using CalendarCalendar cal = Calendar.getInstance();System.out.println("Current date using Calendar = "+cal.getTime());//Get current time in millisecondsSystem.out.println("Current time in milliseconds using Date = "+date.getTime());System.out.println("Current time in milliseconds using Calendar = "+cal.getTimeInMillis());}}

Output of the above program is:

上面程序的输出是:

Current date using Date = Thu Nov 15 13:51:03 PST Current date using Calendar = Thu Nov 15 13:51:03 PST Current time in milliseconds using Date = 1353016263692Current time in milliseconds using Calendar = 1353016263711

Few points to note while getting the current date in java:

在Java中获取当前日期时要注意的几点:

Calendar.getInstance() is more expensive method, so use it only when you need Calendar object. Else use Date object.Calendar.getInstance()是更昂贵的方法,因此仅在需要Calendar对象时才使用它。 否则使用Date对象。 The number of milliseconds isthe number of milliseconds since January 1, 1970, 00:00:00 GMT.毫秒数是自格林威治标准时间1970年1月1日00:00:00以来的毫秒数。 Notice the difference between milliseconds in Calendar and Date object, it’s because of the time taken for java program to create Date and Calendar object. Date object is created first, hence it’s milliseconds value is lower.请注意Calendar和Date对象中毫秒之间的差异,这是由于Java程序创建Date和Calendar对象所花费的时间。 首先创建日期对象,因此其毫秒值较低。 You can use SimpleDateFormat class to format the date in different ways.您可以使用SimpleDateFormat类以不同方式设置日期格式。

Update: If you are working on Java 8, then you should consider using new Date Time API. For more details, please read Java Date Time API Tutorial.

更新:如果您正在使用Java 8,则应考虑使用新的Date Time API。 有关更多详细信息,请阅读Java Date Time API Tutorial 。

翻译自: /703/get-current-date-time-java

java 获取当前日期时间

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。