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 Date
		Date date = new Date();
		System.out.println("Current date using Date = "+date.toString());

		//Get current date using Calendar
		Calendar cal = Calendar.getInstance();
		System.out.println("Current date using Calendar = "+cal.getTime());

		//Get current time in milliseconds
		System.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 2012
Current date using Calendar = Thu Nov 15 13:51:03 PST 2012
Current time in milliseconds using Date = 1353016263692
Current 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 is the 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 。

翻译自: https://www.journaldev.com/703/get-current-date-time-java

java 获取当前日期时间

你可能感兴趣的:(java,大数据,mysql,javascript,编程语言,ViewUI)