Java get time & the most complete summary of time formatting

Java get time & the most complete summary of time formatting

Recently, I have encountered many problems in obtaining the current time in Java, and some have various requirements. Today, I will summarize the methods of obtaining time in Java and the formatting of time output.

Acquisition method

java.util.Date

This is the most commonly used one. We can get the current time directly under the util package and output it after formatting with SimpleDateFormat

//It is realized through the Date package under util
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(dateFormat.format(date));

Formatted output and unformatted output

Obviously, the readability of unformatted code is not as good as that after formatting. In the actual development scenario, different formatting requirements are required. After talking about how to obtain, we will talk about various formatting of time later.

The new features in Java 8 provide three time classes: LocalDate, LocalTime and LocalDateTime

*All three are in Java Under the time package, omit the package name in the subsequent title

LocalDate

If you only need to get the month, year and day, it's best to use this,

//Get the current date
LocalDate localDate = LocalDate.now();
System.out.println(localDate);

His output is yyyy mm DD

You can also construct the specified month, year and day through the construction method

LocalDate localDate1 = LocalDate.of(2077, 7, 17);

The three parameters have been clearly prompted

Of course, you can also use this to get a single month, day, week, etc

int year = localDate.getYear();
int year1 = localDate.get(ChronoField.YEAR);
Month month = localDate.getMonth();
int month1 = localDate.get(ChronoField.MONTH_OF_YEAR);
int day = localDate.getDayOfMonth();
int day1 = localDate.get(ChronoField.DAY_OF_MONTH);
DayOfWeek dayOfWeek = localDate.getDayOfWeek();
int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);

Month and week can be obtained in the specified English format, as above. The output results are as follows

LocalTime

If you only get hours, minutes and seconds, use this~

LocalTime localTime = LocalTime.now();
System.out.println(localTime);

This is also the same. In addition to obtaining the current value, you can also specify the attached value

LocalTime localTime1 = LocalTime.of(13, 51, 10);
System.out.println(localTime1);

The output is as follows

Get smaller range of hours, minutes and seconds

//Get hours
        int hour = localTime.getHour();
        int hour1 = localTime.get(ChronoField.HOUR_OF_DAY);
        //Get points
        int minute = localTime.getMinute();
        int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR);
        //Get seconds
        int second = localTime.getSecond();
        int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE);

The operation is as follows

LocalDateTime

If you want all of them, it's naturally Date+Time=DateTime

Direct acquisition

LocalDateTime now = LocalDateTime.now();
System.out.println(now);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(now.format(formatter2));

Specified time

LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime localDateTime1 = LocalDateTime.of(2077, Month.SEPTEMBER, 7, 17, 17, 17);
LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);
LocalDateTime localDateTime3 = localDate.atTime(localTime);
LocalDateTime localDateTime4 = localTime.atDate(localDate);
//The localTime and localDate here are defined above

Instant

Take seconds

We are most familiar with currentTimeMillis, which is used to calculate the running time of programs, but in Java The Instant class is prepared for us in the time package, which can also take seconds

// Create an Instant object
Instant instant = Instant.now();
// Get seconds
long currentSecond = instant.getEpochSecond();
// Get milliseconds
long currentMilli = instant.toEpochMilli();
//Commonly used
long l = System.currentTimeMillis();

Output condition

Of course, the final System class is still awesome. After all, it is in the System class.

time stamp

The total number of seconds from 00:00:00 on January 1, 1970 Greenwich mean time to now, a total of 10 digits, in seconds

Note: the timestamp generated by Java is 13 bits, and the unit is milliseconds

If you want to get more accurate seconds, there is also a nanoTime in the System

tips (recommended by Alibaba development manual):

In JDK8, the Instant class is recommended for time statistics and other scenarios

Modification time

java. Modification methods of LocalDate, LocalTime, LocalDateTime and Instant class instances under time

We directly click the LocalDate instance and find that it encapsulates many methods

It's not necessary for us to say one by one. Most of them are literal meaning. For example, plusDays, it's natural to add days to the current date to get the date after adding

Are you afraid? The ten day National Day holiday ends directly.

There are many similar methods in other classes, such as firstDayOfYear (the first day of the year) and so on.

Format output

When it comes to the formatted output of dates, the first thing you think of must be

SimpleDateFormat

His usage is countless, but as long as you know the relationship between yyyy DD mm – HH mm SS, you can output as you want.

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <h3>firstIdeaProject</h3>
 * <p></p>
 *
 * @author : Nicer_feng
 * @date : 2020-09-28 10:21
 **/
public class SimpleDateFormatDemo {
    public static void main(String[] args) {
        SimpleDateFormat myFmt=new SimpleDateFormat("yyyy year MM month dd day HH Time mm branch ss second");
        SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm");
        SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //Equivalent to now toLocaleString()
        SimpleDateFormat myFmt3=new SimpleDateFormat("yyyy year MM month dd day HH Time mm branch ss second E ");
        SimpleDateFormat myFmt4=new SimpleDateFormat("The third day of the year D Day of the year w The first day of the month W A week in a day k Time z time zone");
        SimpleDateFormat myFmt5=new SimpleDateFormat("This year is yyyy,This month is MM Month, today is dd No");
        Date now=new Date();
        System.out.println(myFmt.format(now));
        System.out.println(myFmt1.format(now));
        System.out.println(myFmt2.format(now));
        System.out.println(myFmt3.format(now));
        System.out.println(myFmt4.format(now));
        System.out.println(myFmt5.format(now));
        System.out.println(now.toString());
        System.out.println(now.toGMTString());
        System.out.println(now.toLocaleString());
    }
}

Note that the last two methods here are outdated, and the output is as follows

The following summarizes the meaning of each letter in SimpleDateFormat

SimpleDateFormat function variable / mode letter

G age marker
y year
M month
d day
h in the morning or afternoon (1 ~ 12)
H hour in one day (0 ~ 23)
m points
s seconds
S MS
E week
D day of the year
F what is the week of the month
w what week of the year
W what week of the month
a AM / PM marker
k hour in a day (1 ~ 24)
K o'clock in the morning or afternoon (0 ~ 11)
z time zone

For more complete information, see the SimpleDateFormat class in jdk8 API

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

I have talked so much about SimpleDateFormat, but in fact, it is not recommended in JDK8. Why, because SimpleDateFormat is thread unsafe. Therefore, we recommend using Instant instead of Date, LocalDateTime with Calendar, and DateTimeFormatter instead of SimpleDateFormat in JDK8 applications. The official explanation is simple beautiful strong immutable thread safe.

DateTimeFormatter (important)

It is basically the same as the SimpleDateFormat function variable above. Write a simple demo

LocalDate localDate = LocalDate.now();
        String format1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
        //yyyyMMdd
        String format2 = localDate.format(DateTimeFormatter.ISO_DATE);
        //yyyy-MM-dd
        //2.LocalTime  --> String
        LocalTime localTime = LocalTime.now();
        String format3 = localTime.format(DateTimeFormatter.ISO_TIME);
        //20:19:22.42
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
        String format4 = localTime.format(formatter);
        //3.LocalDateTime  --> String
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String format5 = localDateTime.format(formatter2);

        System.out.println(format1);
        System.out.println(format2);
        System.out.println(format3);
        System.out.println(format4);
        System.out.println(format5);

output

This DateTimeFormatter can even be output according to local customs

LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy MMM dd EE HH:mm", Locale.CHINA);
        String format5 = localDateTime.format(formatter2);

output

However, the official does not always meet our expectations, so it is recommended to encapsulate the DateTimeUtils class to call

DateTimeUtils encapsulation

DateTimeUtils.java

package TimeUtilssss;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

/**
 * <h3>firstIdeaProject</h3>
 * <p></p>
 *
 * @author : Nicer_feng
 * @date : 2020-09-28 10:48
 **/
public class DateTimeUtils {
    public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HHmmss");
    public static final DateTimeFormatter YEAR_MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM");
    public static final DateTimeFormatter SHORT_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyMMdd");
    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final DateTimeFormatter SHORT_DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyMMddHHmmss");
    public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static final DateTimeFormatter LONG_DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS");

    /**
     * Returns the current date
     */
    public static LocalDate getCurrentLocalDate() {
        return LocalDate.now();
    }

    /**
     * Returns the current time
     */
    public static LocalTime getCurrentLocalTime() {
        return LocalTime.now();
    }

    /**
     * Returns the current date and time
     */
    public static LocalDateTime getCurrentLocalDateTime() {
        return LocalDateTime.now();
    }

    /**
     * yyyy-MM-dd
     */
    public static String getCurrentDateStr() {
        return LocalDate.now().format(DATE_FORMATTER);
    }

    /**
     * yyMMdd
     */
    public static String getCurrentShortDateStr() {
        return LocalDate.now().format(SHORT_DATE_FORMATTER);
    }

    public static String getCurrentMonthStr() {
        return LocalDate.now().format(YEAR_MONTH_FORMATTER);
    }

    /**
     * yyyy-MM-dd HH:mm:ss
     */
    public static String getCurrentDateTimeStr() {
        return LocalDateTime.now().format(DATETIME_FORMATTER);
    }


    public static String getCurrentLongDateTimeStr(){
        return LocalDateTime.now().format(LONG_DATETIME_FORMATTER);
    }

    /**
     * yyMMddHHmmss
     */
    public static String getCurrentShortDateTimeStr() {
        return LocalDateTime.now().format(SHORT_DATETIME_FORMATTER);
    }

    /**
     * HHmmss
     */
    public static String getCurrentTimeStr() {
        return LocalTime.now().format(TIME_FORMATTER);
    }

    public static String getCurrentDateStr(String pattern) {
        return LocalDate.now().format(DateTimeFormatter.ofPattern(pattern));
    }

    public static String getCurrentDateTimeStr(String pattern) {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(pattern));
    }

    public static String getCurrentTimeStr(String pattern) {
        return LocalTime.now().format(DateTimeFormatter.ofPattern(pattern));
    }

    public static LocalDate parseLocalDate(String dateStr, String pattern) {
        return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
    }

    public static LocalDateTime parseLocalDateTime(String dateTimeStr, String pattern) {
        return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
    }

    public static LocalTime parseLocalTime(String timeStr, String pattern) {
        return LocalTime.parse(timeStr, DateTimeFormatter.ofPattern(pattern));
    }

    public static String formatLocalDate(LocalDate date, String pattern) {
        return date.format(DateTimeFormatter.ofPattern(pattern));
    }

    public static String formatLocalDateTime(LocalDateTime datetime, String pattern) {
        return datetime.format(DateTimeFormatter.ofPattern(pattern));
    }

    public static String formatLocalTime(LocalTime time, String pattern) {
        return time.format(DateTimeFormatter.ofPattern(pattern));
    }

    public static LocalDate parseLocalDate(String dateStr) {
        return LocalDate.parse(dateStr, DATE_FORMATTER);
    }

    public static LocalDateTime parseLocalDateTime(String dateTimeStr) {
        return LocalDateTime.parse(dateTimeStr, DATETIME_FORMATTER);
    }

    public static LocalDateTime parseLongLocalDateTime(String longDateTimeStr){
        return LocalDateTime.parse(longDateTimeStr, LONG_DATETIME_FORMATTER);
    }

    public static LocalTime parseLocalTime(String timeStr) {
        return LocalTime.parse(timeStr, TIME_FORMATTER);
    }

    public static String formatLocalDate(LocalDate date) {
        return date.format(DATE_FORMATTER);
    }

    public static String formatLocalDateTime(LocalDateTime datetime) {
        return datetime.format(DATETIME_FORMATTER);
    }

    public static String formatLocalTime(LocalTime time) {
        return time.format(TIME_FORMATTER);
    }

    /**
     * The date is seconds apart
     */
    public static long periodHours(LocalDateTime startDateTime,LocalDateTime endDateTime){
        return Duration.between(startDateTime, endDateTime).get(ChronoUnit.SECONDS);
    }

    /**
     * Days between dates
     */
    public static long periodDays(LocalDate startDate, LocalDate endDate) {
        return startDate.until(endDate, ChronoUnit.DAYS);
    }

    /**
     * Number of weeks between dates
     */
    public static long periodWeeks(LocalDate startDate, LocalDate endDate) {
        return startDate.until(endDate, ChronoUnit.WEEKS);
    }

    /**
     * Months between dates
     */
    public static long periodMonths(LocalDate startDate, LocalDate endDate) {
        return startDate.until(endDate, ChronoUnit.MONTHS);
    }

    /**
     * Number of years between dates
     */
    public static long periodYears(LocalDate startDate, LocalDate endDate) {
        return startDate.until(endDate, ChronoUnit.YEARS);
    }

    /**
     * Is it the same day
     */
    public static boolean isToday(LocalDate date) {
        return getCurrentLocalDate().equals(date);
    }
    /**
     * Gets the current number of milliseconds
     */
    public static Long toEpochMilli(LocalDateTime dateTime) {
        return dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    /**
     * Judge whether it is a leap year
     */
    public static boolean isLeapYear(LocalDate localDate){
        return localDate.isLeapYear();
    }
}

After instantiating the LocalDate class, you can call format directly

Timestamp formatting

What can we do after we get the 13 bit timestamp in Java?

long l = System.currentTimeMillis();
System.out.println(l);
//output 	 one trillion and six hundred and one billion two hundred and sixty million six hundred and ninety thousand seven hundred and seventy-three

Just now, we said that the normal timestamp is 10 bits, and the more than 3 bits in Java are in the millisecond level. What if we don't output millisecond directly? Of course, you can lose the last three digits. You can divide 1000 directly, or convert the timestamp into a string and take only the first ten digits

long l = System.currentTimeMillis();
System.out.println(l);
System.out.println(l/1000);
String l1 = (l + "").substring(0, 10);
System.out.println(l1);

Our timestamp can also be formatted directly with SimpleDateFormat. Here is a demonstration. See the above for other specific operations

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = format.format(l);
System.out.println(s);

reference material:

Alibaba Java development manual Taishan Edition

DateTimeUtil utility class from

https://blog.csdn.net/tanhongwei1994/article/details/86680845

Tags: Java Programming JDK encapsulation

Posted by MHardeman25 on Sat, 14 May 2022 10:50:12 +0300