Date time

1. Date tool Date

import java.utli.Date;

1.1 Usage of date tool

About the instantiation year, month, week, hour, minute, and second, the three special ones are as follows: (get***)

  • getYear()+1900;
  • getMonth()+1;
  • getDay(): For Sunday, getDay returns 0, and Monday returns 1. The solution at this time is dayWeek = (dayWeek == 0)? 7: dayWeek;

【Code】

		......
		Date date = new Date();//创建一个新的日期实例,默认保存的是系统时间
		System.out.println(date);
		int year = date.getYear() + 1900;
		System.out.println(year);
		int month = date.getMonth() + 1;
		System.out.println(month);
		int dayWeek = date.getDay();
		dayWeek = (dayWeek == 0) ? 7 : dayWeek;
		System.out.println(dayWeek);

In addition to the above get*** method, Date also provides a certain time value set*** for setting date instantiation

		Date date = new Date(); // 创建一个新的日期实例,默认保存的是系统时间
		date.setYear(100); // 设置日期实例中的年份
		int year = date.getYear() + 1900; // 获取日期实例中的年份
		System.out.println("year=" + year);
		date.setMonth(10); // 设置日期实例中的月份
		int month = date.getMonth() + 1; // 获取日期实例中的月份
		System.out.println("month=" + month);
		date.setDate(20); // 设置日期实例中的日子
		int dateInt = date.getDate(); // 获取日期实例中的日子
		System.out.println("dateInt=" + dateInt);
		date.setHours(12); // 设置日期实例中的时钟
		int hour = date.getHours(); // 获取日期实例中的时钟
		System.out.println("hour=" + hour);
		date.setMinutes(30); // 设置日期实例中的分钟
		int minute = date.getMinutes(); // 获取日期实例中的分钟
		System.out.println("minute=" + minute);
		date.setSeconds(59); // 设置日期实例中的秒钟
		int second = date.getSeconds(); // 获取日期实例中的秒钟
		System.out.println("second=" + second);
		date.setTime(1000);
		long time = date.getTime();

Have you ever thought about how to compare which time is earlier and which time is later?

As the name implies, you can use the equals method, before method and after method. In order to reduce the memory space, we might as well unify them, so there is a Date typecompareToMethod, the method returns -1 means A time is earlier; returns 0 means the two are the same; returns 1 means B time is earlier.

【Code】

		// 比较两个日期时间的先后关系
		private static void compareDate() {
    
    
		Date dateOld = new Date(); // 创建一个日期实例
		Date dateNew = new Date(); // 创建一个日期实例
		// 设置dateNew的时间总数(单位毫秒)。此处表示给当前时间增加一毫秒
		dateNew.setTime(dateNew.getTime() + 1);
		/*boolean equals = dateOld.equals(dateNew); // 比较两个时间是否相等
		System.out.println("equals=" + equals);
		boolean before = dateOld.before(dateNew); // 比较A时间是否在B时间之前
		System.out.println("before=" + before);
		boolean after = dateOld.after(dateNew); // 比较A时间是否在B时间之后
		System.out.println("after=" + after);*/
		// 比较A时间与B时间的先后关系。
		// 返回-1表示A时间较早,返回0表示两个时间相等,返回1表示B时间较早
		int compareResult = dateOld.compareTo(dateNew);
		System.out.println("compareResult=" + compareResult);
	}

1.2 Date and time format

In order to meet the needs of users, such as "2020-12-04 23:06:32", "December 04, 2020" and so on.
This requires the use of Java to provide special date formatting toolsSimpleDateFormat

import java.text.SimpleDateFormat;
  • Create a formatting example with specified rules for the tool
  • Then call the format method to convert a date instance into a string in the specified format
	// 获取当前的日期时间字符串
	public static String getNowDateTime() {
    
    
		// 创建一个日期格式化的工具
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//yyyy年MM月dd日...或yyyy-MM-dd或HH:mm:ss或HH:mm:ss.SSS
		// 将当前日期时间按照指定格式输出格式化后的日期时间字符串
		return sdf.format(new Date());
	}

The following is the definition of the date and time format:

  • Lowercase yyyy: represents the 4-digit year number
  • Uppercase MM: represents two digits of the month
  • Lowercase dd: represents two date numbers
  • Capital HH: indicates a 24-hour clock
  • Lowercase hh: means 12-hour clock
  • Lowercase mm: represents two-digit minutes
  • Lowercase ss: represents two-digit seconds
  • Uppercase SSS: represents 3 milliseconds

It can be seen from the above that the use of SimpleDateFormat to convert the date type to the string type, not only can be converted in this way, but also the string type can be converted to the date type, then you need to call parse method.

import jav.text.ParseException;
...throws ParseException
  • First create a formatted instance of the specified tag;
  • Then call the parse method of this instance to convert a string in a corresponding format into a date instance.

【Code】

		String str = "2019-11-25 11:18:53";
		// 创建一个日期格式化的工具
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dateFromStr = sdf.parse(str); // 从字符串中按照指定格式解析日期时间信息

2. Calendar tool Calendar

import java.utli.Calendar;

2.1 Usage of Calendar Tool

  • getInstance(): Create a calendar instance instead of the new keyword
  • get(): Get the specific value of the specified time unit, such as Calendar.YEAR, Calendar.DAY_OF_WEEK,...
	Calendar calendar = Calendar.getInstance(); // 创建一个日历实例
	int year = calendar.get(Calendar.YEAR); // 获取日历实例中的年份
	System.out.println("year=" + year);

Pay attention to two points:

  • Calendar's month still counts from 0, so to get the code of the month, you need +1;
	int month = calendar.get(Calendar.MONTH) + 1; // 获取日历实例中的月份
	System.out.println("month=" + month);
  • The day of the week of Calendar is counted from 1, Sunday is 1, and Monday is 2 (different from Date), and it does not conform to the habits of Chinese people, so the following code is used to solve it:
	int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // 获取日历实例中的星期几
	dayOfWeek = dayOfWeek == 1 ? 7 : dayOfWeek - 1;
	System.out.println("dayOfWeek=" + dayOfWeek);

In addition, compared with Date, Calendar has new types: Calendar.DAY_OF_YEAR(Days counted from the beginning of the year),Calendar.MILLISECOND(Milliseconds after the second),Calendar.HOUR(Clock value in twelve-hour clock),Calendar.HOUR_OF_DAY(The clock value of the 24-hour clock)

		......
		int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); // 获取日历实例中从年初开始数的日子
		System.out.println("dayOfYear=" + dayOfYear);
		int hour = calendar.get(Calendar.HOUR); // 获取日历实例中的时钟(12小时制)
		System.out.println("hour=" + hour);
		int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 获取日历实例中的时钟(24小时制)
		System.out.println("hourOfDay=" + hourOfDay);
		int minute = calendar.get(Calendar.MINUTE); // 获取日历实例中的分钟
		System.out.println("minute=" + minute);
		int second = calendar.get(Calendar.SECOND); // 获取日历实例中的秒钟
		System.out.println("second=" + second);
		int milliSecond = calendar.get(Calendar.MILLISECOND); // 获取日历实例中的毫秒
		System.out.println("milliSecond=" + milliSecond);

Finally, have you ever thought that in order to change a specific date, you need to use set () and get () two methods, first obtain the current time value through the get method, and then pass the current value to the set method after increasing or decreasing Achieve their goals.

The set method is used to set the value:

  • The set method with 3 parameters supports setting the year, month and day at the same time
  • The set method with 6 parameters supports setting the year, month, day, hour, minute, and second at the same time
  • The set method with 2 parameters can change the time unit of a specified value [first parameter: unit type, second parameter: specific time value]
		Calendar calendar = Calendar.getInstance(); // 创建一个日历实例
		// 调用带三个参数的set方法同时设置日历实例的年、月、日
		calendar.set(2020, 12, 06);
		// 调用带六个参数的set方法同时设置日历实例的年、月、日、时、分、秒
		calendar.set(2020, 12, 06, 23, 42, 40);
		System.out.println("begin set dayOfMonth="
				+ calendar.get(Calendar.DAY_OF_MONTH));
		// 带两个参数的set方法允许把某个时间单位改为指定数值
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		System.out.println("end set dayOfMonth=" + calendar.get(Calendar.DAY_OF_MONTH));
		System.out.println("begin set hourOfDay=" + calendar.get(Calendar.HOUR_OF_DAY));

The combined use of get and set methods can achieve its purpose, but simple functions have to be completed in two steps. In order to optimize them, Calendar provides an add method that allows direct setting of relative values.

	// 调用add方法,直接在当前时间的基础上增加若干数值
	calendar.add(Calendar.MINUTE, 10);
	System.out.println("end add minute=" + calendar.get(Calendar.MINUTE));

Another point is that the Calendar tool retains the methods related to Date time verification. The usage is consistent with the method of the same name of the Date type, as shown in the following code:

	// 比较两个日历时间的先后关系
	private static void compareCalendar() {
    
    
		Calendar calendarOld = Calendar.getInstance(); // 创建一个日历实例
		Calendar calendarNew = Calendar.getInstance(); // 创建一个日历实例
		calendarNew.add(Calendar.SECOND, 1); // 给calendarNew加上一秒
		boolean equals = calendarOld.equals(calendarNew); // 比较两个时间是否相等
		System.out.println("equals=" + equals);
		boolean before = calendarOld.before(calendarNew); // 比较A时间是否在B时间之前
		System.out.println("before=" + before);
		boolean after = calendarOld.after(calendarNew); // 比较A时间是否在B时间之后
		System.out.println("after=" + after);
		// 比较A时间与B时间的先后关系。
		// 返回-1表示A较早,返回0表示二者相等,返回1表示B较早
		int compareResult = calendarOld.compareTo(calendarNew);
		System.out.println("compareResult=" + compareResult);
	}

2.2 Common applications of calendar tools

2.2.1 Conversion between Calendar type and Date type

Using Calendar’s getTime method and setTime method, the return value of the getTime method is an instance of the Date type, and the input parameter of the setTime method is an instance of the Date.

	// 把Calendar类型的数据转换为Date类型
	private static void convertCalendarToDate() {
    
    
		Calendar calendar = Calendar.getInstance(); // 创建一个日历实例
		Date date = calendar.getTime(); // 调用日历实例的getTime方法,获得日期信息
		System.out.println("日历转日期 date=" + date.toString() + ", calendar=" + calendar.toString());
	}

	// 把Date类型的数据转换为Calendar类型
	private static void convertDateToCalendar() {
    
    
		Calendar calendar = Calendar.getInstance(); // 创建一个日历实例
		Date date = new Date(); // 创建一个日期实例
		calendar.setTime(date); // 调用日历实例的setTime方法,设置日期信息
		System.out.println("日期转日历 date=" + date.toString() + ", calendar=" + calendar.toString());
	}

2.2.2 Calculate the number of days between two calendar times

Calculating the number of days between two calendar times is very common in business, such as: advance reminders of credit card repayment dates, website accounts have to log in again after several days, etc.

At this time, you need to use CalendargetTimeInMillis方法, The method returns the total time measured in milliseconds.

	// 计算两个日历实例间隔的天数
	private static void countDays() {
    
    
		Calendar calendarA = Calendar.getInstance(); // 创建一个日历实例
		calendarA.set(2019, 3, 15); // 设置第一个日历实例的年月日
		Calendar calendarB = Calendar.getInstance(); // 创建一个日历实例
		calendarB.set(2019, 9, 15); // 设置第二个日历实例的年月日
		long timeOfA = calendarA.getTimeInMillis(); // 获得第一个日历实例包含的时间总数(单位毫秒)
		long timeOfB = calendarB.getTimeInMillis(); // 获得第二个日历实例包含的时间总数(单位毫秒)
		// 先计算二者的差额,再把毫秒计量的差额转换为天数
		long dayCount = (timeOfB - timeOfA) / (1000 * 60 * 60 * 24);
		System.out.println("dayCount=" + dayCount);
	}

2.2.3. Print the current month calendar

The NI year, month and week in the monthly calendar are clear, only the day at the end of the month changes. In order to more easily determine the last day of the month end, Calendar providesgetActualMaximum method, This method is used to obtain the maximum legal value of the specified time unit. If the specified time unit is Calenda.DATE, it will return the last day of the month. The code is as follows:

int lastDay = calendar.getActualMaximum(Calendar.DATE); // 获取当月的最后一天

All the elements of the next monthly calendar are complete, including the current year, the current month, the first day of the current month, and the last day of the current month. Then arrange the days in the middle in order of week.

	// 打印当前月份的月历
	private static void printMonthCalendar() {
    
    
		Calendar calendar = Calendar.getInstance(); // 创建一个日历实例
		calendar.set(Calendar.DATE, 1); // 设置日期为当月1号
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // 获得该日期对应的星期几
		dayOfWeek = dayOfWeek == 1 ? 7 : dayOfWeek - 1;
		int lastDay = calendar.getActualMaximum(Calendar.DATE); // 获取当月的最后一天
		// 拼接月历开头的年月
		String yearAndMonth = String.format("\n%21s%d年%d月", "",
				calendar.get(calendar.YEAR), calendar.get(calendar.MONTH) + 1);
		System.out.println(yearAndMonth);
		System.out.println(" 星期一 星期二 星期三 星期四 星期五 星期六 星期日");
		for (int i = 1; i < dayOfWeek; i++) {
    
     // 先补齐1号前面的空白
			System.out.printf("%7s", "");
		}
		for (int i = 1; i <= lastDay; i++) {
    
     // 循环打印从一号到本月最后一天的日子
			String today = String.format("%7d", i);
			System.out.print(today);
			if ((dayOfWeek + i - 1) % 7 == 0) {
    
     // 如果当天是星期日,末尾就另起一行
				System.out.println();
			}
		}
	}

Guess you like

Origin blog.csdn.net/weixin_46312449/article/details/110674484