Java Date overview and construction method

Date class

Date java.util package provides classes to encapsulate the current date and time. Date class provides two constructors Date object to instantiate other outdated

1, construction method

 

  • The first constructor current date and time used to initialize the object.
Date( )
  • Receiving a second constructor parameter, which is the number of milliseconds since January 1, 1970 is.
Date(long millisec)

Test code is as follows:

package cn.wen;

import java.util.Date;

public class DateDemo {
	public static void main(String[] args) {
		// 创建对象
		Date d = new Date();
		System.out.println("d:" + d);	//d:Sun Jan 05 14:47:29 CST 2020

		// 创建对象
		//long time = System.currentTimeMillis();	//d2:Thu Jan 01 09:00:00 CST 1970
		long time = 1000 * 60 * 60; // 1小时
		Date d2 = new Date(time);
		System.out.println("d2:" + d2);	 //d2:Thu Jan 01 09:00:00 CST 1970(时差为8小时)
	}
}

2, members of the method

Many are outdated, there are two common understanding of election

  • public long getTime()
  • public void setTime(long time)
package cn.wen;

import java.util.Date;

/*
 * public long getTime():获取时间,以毫秒为单位
 * public void setTime(long time):设置时间
 * 
 * 从Date得到一个毫秒值
 * 		getTime()
 * 把一个毫秒值转换为Date
 * 		构造方法
 * 		setTime(long time)
 */
public class DateDemo {
	public static void main(String[] args) {
		// 创建对象
		Date d = new Date();

		// 获取时间
		long time = d.getTime();
		System.out.println(time);
		System.out.println(System.currentTimeMillis());	 //也可以实现获取当前系统时间

		System.out.println("d:" + d);
		// 设置时间
		d.setTime(1000);	//1000毫秒等于1秒
		System.out.println("d:" + d);
	}
}
1578207470708
1578207470708
d:Sun Jan 05 14:57:50 CST 2020
d:Thu Jan 01 08:00:01 CST 1970

 

Published 91 original articles · won praise 16 · views 1181

Guess you like

Origin blog.csdn.net/hewenqing1/article/details/103842942