Formatting date and time through the DateTimeFormatter formatter

Formatting date and time through the DateTimeFormatter formatter

Title requirements:

Use the scanner to get the input time (time of day, month, year), which is in the common format. Then format the time, and output the formatted time to the console. You can repeat the input time in the console. The formatted time refers to the display time of the Enterprise Wechat record.

Knowledge needs

  1. java Basics
  2. Scanner Scanner
  3. Common class, enumerated class
  4. final modifier
  5. regular expression
  6. DateTimeFormatter Formatter (Formatting and parsing knowledge)
  7. Packaging Class, Print Object
  8. A series of common methods, etc.

Implement Ideas and Simple Steps

  1. Get the scanner, get the time input through the scanner (year, month, day, time)
  2. Create a Notice class (hint class) to access the complete hint information to be used during datetime formatting (common class, enumeration class)
  3. Create a Regex enumeration class that matches a regular expression for date-time, matches the incoming date-time with the corresponding regular expression, passes the matched date-time into the Date-Time Tool Class's method for getting date-time, and then formats it specifically
  4. The format of this time is the common format, then format this time, output the formatted time to the console, you can repeat the input time in the console. The formatted time refers to the display time of Enterprise WeChat records.
  5. Need to be implemented:
    In the same year:
    Same month: month day + hour
    Today: Morning/Afternoon+Hour
    Tomorrow: Tomorrow + Hour
    Yesterday: Yesterday + Hour
    Week before today (including today): Week + Hour
    At different months:
    Last month (tested by adjusting time):
    Today: Morning/Afternoon+Hour
    Tomorrow: Tomorrow + Hour
    Yesterday: Yesterday + Hour
    Week before today (including today): Week + Hour
    Month: Month Day + Hour
    Next month (by adjusting the time to test):
    Tomorrow: Tomorrow + Hour
    Other Months: Month Day + Hour
    Different years: year, month, day + hour

The program test scenarios are as follows:

Welcome to Date Time Formatter!
If you exit the program, enter'exit'or'exit'!
Refer to the display time of Enterprise WeChat chat records, enter a legal time:
The legal time format is date format yyy.MM.dd HH:mm
         Examples: 2020.1.10 19:19
    Or date format yyyy-MM-dd HH:mm
         Examples: 2020-1-10 19:19
    Or date format yyyy/MM/dd HH:mm
         Examples: 2020/1/10 19:19
 Please enter:
2020/1/11 19:19
 The date and time after formatting is:
          19:19 p.m.
If you exit the program, enter'exit'or'exit'!
2020/1/12 19:19
 The date and time after formatting is:
          Tomorrow 19:19
 If you exit the program, enter'exit'or'exit'!
2020/1/10 19:19
 The date and time after formatting is:
          Yesterday 19:19
 If you exit the program, enter'exit'or'exit'!
2020/1/9 19:19
 The date and time after formatting is:
          Thursday 19:19
 If you exit the program, enter'exit'or'exit'!
2020/1/3 19:19
 The date and time after formatting is:
          January 3 19:19
 If you exit the program, enter'exit'or'exit'!
2020/2/29 19:19
 The date and time after formatting is:
          February 29 19:19
 If you exit the program, enter'exit'or'exit'!
2019/2/28 19:19
 The date and time after formatting is:
          19:19 February 28, 2019
 If you exit the program, enter'exit'or'exit'!

If other situations are needed, test yourself!

The implementation code is as follows:

Test Class
package datetimeformatter;

/**
 * Date Time Test Class <br>
 * 2020 January 10, 2001 9:43:16 a.m.
 * 
 * @author zcf
 * @version 1.0
 */
public class Test {
	/**
	 * Program Entry
	 * 
	 * @param args Entry parameters
	 */
	public static void main(String[] args) {
		/**
		 * Enter Time Formatter
		 */
		DateTime.startIn();
	}
}
//Date Time Class
package datetimeformatter;

import java.util.Scanner;

/**
 * Date Time Class <br>
 * 2020 January 10, 2001 9:44:13 a.m.
 * 
 * @author zcf
 * @version 1.0
 */
public class DateTime {
	/**
	 * Leap year Date regular
	 */
	private static final String LEEP_YEAR = Regex.LEEP_YEAR.getDesc();

	/**
	 * Ordinary Year Date Regular
	 */
	private static final String COMMON_YEAR = Regex.COMMON_YEAR.getDesc();
	/**
	 * Time Regular
	 */
	private static final String TIME = Regex.TIME.getDesc();

	/**
	 * Private constructor cannot create instance
	 */
	private DateTime() {

	}

	/**
	 * Time Formatter, Start Method
	 */
	public static void startIn() {
		// Prompt to enter the program
		Notice.inTip();
		// Get Scanner
		Scanner sc = new Scanner(System.in);
		// Determine if there is next line of input
		while (sc.hasNextLine()) {
			// Gets the date and time of the next line input
			// The trim() method ignores unnecessary spaces before and after console output
			String dateTime = sc.nextLine().trim();
			if (dateTime.matches("exit|Sign out")) {
				// Exit the program
				Notice.printNotice(Notice.EXIT_FINASH);
				// Turn off scanner
				sc.close();
				break;
			}
			// Regular expression that matches the incoming date-time
			else if ((dateTime.matches(LEEP_YEAR + TIME)) || (dateTime.matches(COMMON_YEAR + TIME))) {
				// Pass the matched time into the tool class's method of getting the date and time
				DateTimeTool.getDateTime(dateTime);
				// Exit the program
				Notice.printNotice(Notice.EXIT_PROGRAM);
				continue;
			} else {
				// Match failed with error
				Notice.printNotice(Notice.DATE_TIME_ERROR);
				// Exit Available
				Notice.printNotice(Notice.EXIT_PROGRAM);
			}
		}
	}
}
//Information Prompt Class
package datetimeformatter;

/**
 * Complete program hints <br>
 * 2020 10:51:28 January, 2001
 * 
 * @author zcf
 * @version 1.0
 */
public class Notice {
	/**
	 * Exit Program Indicator
	 */
	public static final String EXIT_PROGRAM = "If you quit the program,Please enter'exit'or'Sign out' !";
	/**
	 * Exit Program Completion Indicator
	 */
	public static final String EXIT_FINASH = "Exited program,Welcome to Next Use!";
	/**
	 * Date Error Indicator
	 */
	public static final String DATE_ERROR = "Date error";
	/**
	 * Date Separator Error Indicator
	 */
	public static final String DATE_SPLIT_ERROR = "Date Separator Error,Please re-enter:\n";
	/**
	 * Time Error Indicator
	 */
	public static final String TIME_ERROR = "Time Error";
	/**
	 * Date Time Error Indicator
	 */
	public static final String DATE_TIME_ERROR = "Illegal date and time,Please re-enter:\n";

	/**
	 * Small tip to enter the program
	 */
	public static void inTip() {
		System.out.println("Welcome to Date Time Formatter!");
		//Quit program prompt
		System.out.println(Notice.EXIT_PROGRAM);
		System.out.println("Refer to the display time of the chat records of Enterprise WeChat,Enter a valid time:");
		System.out.println("The legal time format is date format is yyyy.MM.dd HH:mm\n         Form like:2020.1.10 19:19");
		System.out.println("    Or date format is yyyy-MM-dd HH:mm\n         Form like:2020-1-10 19:19");
		System.out.println("    Or date format is yyyy/MM/dd HH:mm\n         Form like:2020/1/10 19:19");
		System.out.println("Please enter:");
	}

	/**
	 * Method of Output Prompt Information
	 * 
	 * @param printNotice Tips to output
	 */
	public static void printNotice(String printNotice) {
		//Output prompt information
		System.out.println(printNotice);
	}
}

//Match Date Time Regular Expression Class
/**
	 * Verify that a regular expression leap year in the format YYYY.MM.DD HH:MM can be divided by 4 but not by 100, <br>
	 * ((([0-9]{2}(0[48]|[2468][048]|[13579][26])) Leap year, divisible by 400 < br>
	 * |((0[48]|[2468][048]|[13579][26])00) Match leap year February 29.If this is not the day, match validation is continued by the following formula.<br>
	 * [-\\/\\.]0?2[-\\/\\.]29 <br>
	  * Average year (0001-9999) < br>
	 * |([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})<br>
	  * Month day, 31 days [-\/\] (((0?[13578]|1[02]) [-\/\] (0?[1-9]|[12][0-9]|3[01]) <br>
	   * Month day, April, June, September, and November have 30 days | ((0?[469]|11) [-\/\\] (0?[1-9]|[12][0-9]|30)) <br>
	  * February <br>
	 * |(0?2[-\\/\\.](0?[1-9]|[1][0-9]|2[0-8])))) <br>
	  * Time (([01]?[0-9]|2[0-3]): [0-5]?[0-9])
	 */
package datetimeformatter;

/**
 * Time Date Matching Regular Expression <br>
 * 2020 January 10, 2001 6:21:44 p.m.
 * 
 * @author zcf
 * @version 1.0
 */
public enum Regex {
	/**
	 * Match leap years
	 */
	LEEP_YEAR("(([0-9]{2}(0[48]|[2468][048]|[13579][26]))"
			+ "|((0[48]|[2468][048]|[13579][26])00))[-\\/\\.]0?2[-\\/\\.]29"),
	/**
	 * Match flat year
	 */
	COMMON_YEAR("|([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})"
			+ "[-\\/\\.](((0?[13578]|1[02])[-\\/\\.](0?[1-9]|[12][0-9]|3[01]))"
			+ "|((0?[469]|11)[-\\/\\.](0?[1-9]|[12][0-9]|30))" 
			+ "|(0?2[-\\/\\.](0?[1-9]|[1][0-9]|2[0-8])))"),
	/**
	 * Match time
	 */
	TIME(" (([01]?[0-9]|2[0-3]):[0-5]?[0-9])");
	/**
	 * Information Description
	 */
	private final String desc;

	/**
	 * Parametric constructor
	 * 
	 * @param desc Information Description Parameters
	 */
	private Regex(String desc) {
		this.desc = desc;
	}

	/**
	 * Getting information description parameters
	 * 
	 * @return Information Description
	 */
	public String getDesc() {
		return desc;
	}
}
//Format Date Time Class
package datetimeformatter;

import java.time.LocalDateTime;
import java.time.MonthDay;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

/**
 * Date Time Tool Class <br>
 * 2020 11:12:19 a.m. on January 10, 2001
 * 
 * @author zcf
 * @version 1.0
 */
public class DateTimeTool {
	/**
	 * Current year
	 */
	private static int currentYear = Year.now().getValue();
	/**
	 * Current month
	 */
	private static int currentMonth = MonthDay.now().getMonth().getValue();
	/**
	 * Current day
	 */
	private static int currentDay = MonthDay.now().getDayOfMonth();
	/**
	 * February
	 */
	private static int[] bigMonth = { 1, 3, 5, 7, 8, 10, 12 };
	/**
	 * Small Month
	 */
	private static int[] smallMonth = { 4, 6, 9, 11 };

	/**
	 * Get Date Time Method
	 * 
	 * @param dateTime Incoming Date Time
	 * @return Date time after processing
	 */
	public static String getDateTime(String dateTime) {
		String result = null;
		// Split Date Time by Spaces
		String[] dateTStrings = dateTime.split(" ");
		// Date time length must be 2
		if (dateTStrings.length != 2) {
			// Date Time Error Indicator
			Notice.printNotice(Notice.DATE_TIME_ERROR);
			return Notice.DATE_TIME_ERROR;
		}
		// Date after split
		String date = dateTStrings[0];
		// Time after Split
		String time = dateTStrings[1];
		// Separator
		String splitter = "";
		// The delimiter included in the judgment date is -. Or/
		if (date.contains("-")) {
			// Pass-split Date
			splitter = "-";
		} else if (date.contains(".")) {
			// Pass. Split Date
			splitter = "\\.";
		} else if (date.contains("/")) {
			// Pass/Split Date
			splitter = "/";
		} else {
			return Notice.DATE_SPLIT_ERROR;
		}
		// Split incoming dates
		// Ensure that dates are split using the same symbol, for example: <1>yyyy.MM.dd <2>yyyy-MM-dd <3>yyyy/MM/dd
		String[] splitAfDate = date.split(splitter);
		// The incoming time is split by a colon (:)
		String[] splitAfTime = time.split(":");
		// The year, month, day divider for a given date is consistent
		if (splitAfDate.length != 3) {
			// Error returning date when separator is inconsistent
			System.out.println(Notice.DATE_SPLIT_ERROR);
			return Notice.DATE_SPLIT_ERROR;
		} else if (splitAfTime.length != 2) {
			// Time Error
			System.out.println(Notice.TIME_ERROR);
			return Notice.TIME_ERROR;
		} else {
			// Execute normally down when the separators are consistent
			// Incoming Year
			int year = Integer.valueOf(splitAfDate[0]);
			// Incoming Month
			int month = Integer.valueOf(splitAfDate[1]);
			// Incoming Day
			int day = Integer.valueOf(splitAfDate[2]);
			// On Incoming
			int hour = Integer.valueOf(splitAfTime[0]);
			// Incoming Score
			int minute = Integer.valueOf(splitAfTime[1]);

			// Fully stitched date-time
			String inDateTime = year + splitter + month + splitter + day + " " + hour + ":" + minute;
			// Create formatter using pattern string
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("y" + splitter + "M" + splitter + "d" + " H:m");
			// Resolving a time-date string to a date-time object
			LocalDateTime localDateTime = LocalDateTime.parse(inDateTime, formatter);
			// Determine that the incoming year is the same as the current year, the same year
			if (year == currentYear) {
				// Determine if it's the same month
				if (month == currentMonth) {
					if (day == currentDay) {
						// Today, the scenario is as follows:
						printResult("a HH:mm", localDateTime);
					} else if (day - currentDay == 1) {
						// Tomorrow, the scenario is as follows:
						printResult("Tomorrow HH:mm", localDateTime);
					} else if (day - currentDay == -1) {
						// Yesterday, the scene was as follows:
						printResult("Yesterday HH:mm", localDateTime);
					} else if (day - currentDay >= -7 && day - currentDay <= -2) {
						// Within a week from today, including today, the scenario is as follows:
						printResult("E HH:mm", localDateTime);
					} else {
						// Except today, tomorrow, yesterday, and the same month of the previous week today, the scenario is as follows:
						printResult("M month d day HH:mm", localDateTime);
					}
				} else if (month - currentMonth == 1) {
					// Judge next month
					// Judging February of the lunar month and leap year
					// Incoming date is 1
					if (day == 1) {
						// Judging the Tomorrow of the Month
						if (Arrays.binarySearch(bigMonth, currentMonth) >= 0 && currentDay == 31) {
							// Tomorrow, the scenario is as follows:
							printResult("Tomorrow HH:mm", localDateTime);
							// Judging the Tomorrow of Little Month
						} else if (Arrays.binarySearch(smallMonth, currentMonth) >= 0 && currentDay == 30) {
							// Tomorrow, the scenario is as follows:
							printResult("Tomorrow HH:mm", localDateTime);
						} else {
							// February
							if (currentMonth == 2) {
								// Determine whether it is a leap year
								if ((currentYear % 4 == 0 && currentYear % 100 != 0) || currentYear % 400 == 0) {
									// Leap year February is 29 days
									if (currentDay == 29) {
										// Tomorrow, the scenario is as follows:
										printResult("Tomorrow HH:mm", localDateTime);
									} else {
										// In the same month, the scenario was as follows:
										printResult("M month d day HH:mm", localDateTime);
									}
								} else {
									// February is 28 days
									if (currentDay == 28) {
										// Tomorrow, the scenario is as follows:
										printResult("Tomorrow HH:mm", localDateTime);
									} else {
										// In the same month, the scenario was as follows:
										printResult("M month d day HH:mm", localDateTime);
									}
								}
							} else {
								// In the same month, the scenario was as follows:
								printResult("M month d day HH:mm", localDateTime);
							}
						}
					} else {
						// In the same month, the scenario was as follows:
						printResult("M month d day HH:mm", localDateTime);
					}
				} else if (month - currentMonth == -1) {
					// Judge last month
					// Judging February of the lunar month and leap year
					// Currently 1
					if (currentDay == 1) {
						// Judging Yesterday of Great Moon
						if (Arrays.binarySearch(bigMonth, month) >= 0 && day == 31) {
							// Yesterday, the scene was as follows:
							printResult("Yesterday HH:mm", localDateTime);
							// Judging Little Month's Yesterday
						} else if (Arrays.binarySearch(smallMonth, month) >= 0 && day == 30) {
							// Yesterday, the scene was as follows:
							printResult("Yesterday HH:mm", localDateTime);
						} else if (month == 2) {
							// Determine whether it is a leap year
							if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
								// Leap year February is 29 days
								if (day == 29) {
									// Yesterday, the scene was as follows:
									printResult("Yesterday HH:mm", localDateTime);
								}
							} else {
								// February is 28 days
								if (day == 28) {
									// Yesterday, the scene was as follows:
									printResult("Yesterday HH:mm", localDateTime);
								}
							}
						}
						return result;
					}
					// Currently greater than or equal to 7
					if (currentDay >= 7) {
						// In the same month, the scenario was as follows:
						printResult("M month d day HH:mm", localDateTime);
					}
					// The week before the current day
					else if (Arrays.binarySearch(bigMonth, month) >= 0 && 31 - day + currentDay < 7) {
						// Current day and previous week
						// Within a week from today, including today, the scenario is as follows:
						printResult("E HH:mm", localDateTime);
					} else if (Arrays.binarySearch(smallMonth, month) >= 0 && 30 - day + currentDay < 7) {
						// Current day and previous week
						// Within a week from today, including today, the scenario is as follows:
						printResult("E HH:mm", localDateTime);
					} else if (month == 2) {
						// Determine whether it is a leap year
						if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
							// Leap year February is 29 days
							if (29 - day + currentDay < 7) {
								// Current day and previous week
								// Within a week from today, including today, the scenario is as follows:
								printResult("E HH:mm", localDateTime);
							} else {
								// In the same month, the scenario was as follows:
								printResult("M month d day HH:mm", localDateTime);
							}
						} else {
							// February is 28 days
							if (28 - day + currentDay < 7) {
								// Current day and previous week
								// Within a week from today, including today, the scenario is as follows:
								printResult("E HH:mm", localDateTime);
							} else {
								// In the same month, the scenario was as follows:
								printResult("M month d day HH:mm", localDateTime);
							}
						}
					} else {
						// In the same month, the scenario was as follows:
						printResult("M month d day HH:mm", localDateTime);
					}
				} else {
					// In addition to this month, last month and next month, the following scenarios are available:
					printResult("M month d day HH:mm", localDateTime);
				}
			} else {
				// In different years, the scenarios are as follows:
				printResult("yyyy year M month d day HH:mm", localDateTime);
			}
		}
		return result;
	}

	/**
	 * Format DateTime Object as DateTime String
	 * 
	 * @param modeString    Pattern string
	 * @param localDateTime Date Time Object
	 */
	private static void printResult(String modeString, LocalDateTime localDateTime) {
		// Create formatter using pattern string
		DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern(modeString);
		// Format Date Time Object as String
		String formatDateTime = formatter2.format(localDateTime);
		// Output Formatted Date Time String
		System.out.println("Formatted date time is:\n" + "          " + formatDateTime);
	}
}

Four original articles have been published. Praise 5. Visits 55
Private letter follow

Tags: Java

Posted on Fri, 10 Jan 2020 20:53:55 -0500 by viv