The Road to Java - Detailed explanation and application of dates and numbers

Insert image description here


Insert image description here

1. Convert date to number

1. Date

Date 是 Java 标准库中的一个类,提供了处理日期和时间的功能。

getTime(): Returns the number of milliseconds between 00:00:00 GMT on January 1, 1970 and the date and time represented by this Date object.

Date date = new Date();
long timestamp = date.getTime();

toString(): Convert the Date object to a string in the format EEE MMM dd HH:mm:ss zzz yyyy.

Date date = new Date();
String dateString = date.toString();

Mon May 04 09:51:52 CDT 2013

Get the current date and time:

Date currentDate = new Date();
System.out.println("Current Date and Time: " + currentDate);

Compare dates

Date date1 = new Date(); // 当前日期和时间
Date date2 = new Date(1624185600000L); // 2021-06-20 00:00:00

if (date1.equals(date2)) {
    
    
    System.out.println("Dates are equal.");
} else if (date1.before(date2)) {
    
    
    System.out.println("date1 is before date2.");
} else if (date1.after(date2)) {
    
    
    System.out.println("date1 is after date2.");
}

Format date

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(date);
System.out.println("Formatted Date: " + formattedDate);


2. LocalDate

LocalDate is a date class introduced in Java 8 and is part of the java.time package. It is used to represent dates without time and provides rich methods for date calculation, formatting and manipulation.

The following are some common methods and application examples of the LocalDate class:

LocalDate.now(): Get the current date

LocalDate currentDate = LocalDate.now();

LocalDate.of(int year, int month, int dayOfMonth): Construct a LocalDate object based on the specified year, month, and day.

LocalDate date = LocalDate.of(2023, 6, 21);

getYear(), getMonthValue(), getDayOfMonth(): Get the value of year, month and day.

int year = date.getYear();
int month = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();

plusXxx(long amountToAdd), minusXxx(long amountToSubtract): Add and subtract dates, such as increasing/decreasing the number of days, months, etc.

LocalDate newDate = date.plusDays(7); // 增加7天
LocalDate previousDate = date.minusMonths(1); // 减少1个月

isBefore(LocalDate other), isAfter(LocalDate other): Determine the order of dates.

LocalDate date1 = LocalDate.of(2023, 6, 21);
LocalDate date2 = LocalDate.of(2023, 6, 20);

if (date1.isBefore(date2)) {
    
    
    System.out.println("date1 is before date2.");
} else if (date1.isAfter(date2)) {
    
    
    System.out.println("date1 is after date2.");
}

isEqual(LocalDate other): Determine whether two dates are equal.

LocalDate date1 = LocalDate.of(2023, 6, 21);
LocalDate date2 = LocalDate.of(2023, 6, 21);

if (date1.isEqual(date2)) {
    
    
    System.out.println("Dates are equal.");
}

toString(): Convert the LocalDate object to a string in the format of yyyy-MM-dd

LocalDate date = LocalDate.now();
String dateString = date.toString();

Get the current date:

LocalDate currentDate = LocalDate.now();
System.out.println("Current Date: " + currentDate);

Calculate date difference:

LocalDate date1 = LocalDate.of(2023, 6, 21);
LocalDate date2 = LocalDate.of(2023, 6,

2. Convert numbers to dates

1. Instant

The Instant class provides the function of processing precise time points. It can obtain the current time point, create objects at the specified time point, and perform operations such as comparison, calculation, and formatting of time points.

The following are some common methods and application examples of the Instant class:
now():

Instant now = Instant.now();

ofEpochSecond(long epochSecond): Creates an Instant object based on the specified number of seconds.

Instant instant = Instant.ofEpochSecond(1624264800L);

ofEpochMilli(long epochMilli): Creates an Instant object based on the specified number of milliseconds.

Instant instant = Instant.ofEpochMilli(1624264800000L);

getEpochSecond(): Gets the number of seconds since the epoch.

long epochSecond = instant.getEpochSecond();

toEpochMilli(): Gets the number of milliseconds since the epoch.

long epochMilli = instant.toEpochMilli();

isBefore(Instant other): Determine whether the current time point is before another time point.

Instant instant1 = Instant.now();
Instant instant2 = Instant.parse("2023-06-21T12:00:00Z");

if (instant1.isBefore(instant2)) {
    
    
    System.out.println("instant1 is before instant2.");
}

Calculate time difference:

Instant start = Instant.now();

// 执行一些耗时的操作

Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("Time taken: " + duration.getSeconds() + " seconds");

Formatting time:

Instant instant = Instant.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = formatter.format(instant.atZone(ZoneId.systemDefault()));
System.out.println("Formatted DateTime: " + formattedDateTime);

3. Format numbers or dates

1.DecimalFormat class

DecimalFormat(String pattern): Create a DecimalFormat object based on the specified pattern.

DecimalFormat df1 = new DecimalFormat("0.0");   
DecimalFormat df2 = new DecimalFormat("#.#");   
DecimalFormat df3 = new DecimalFormat("000.000");   
DecimalFormat df4 = new DecimalFormat("###.###");   
System.out.println(df1.format(12.34));   
System.out.println(df2.format(12.34));   
System.out.println(df3.format(12.34));   
System.out.println(df4.format(12.34));   

结果:
12.3 
12.3 
012.340 
12.34  

parse(String text) parses the given string into a numerical value.

import java.text.DecimalFormat;
import java.text.ParseException;

public class DecimalFormatExample {
    
    
    public static void main(String[] args) {
    
    
        String formattedNumber = "12,345.67";

        // 创建 DecimalFormat 对象,指定模式 "#,###.##"
        DecimalFormat decimalFormat = new DecimalFormat("#,###.##");

        try {
    
    
            // 使用 .parse() 方法将格式化的字符串解析为数字
            double number = decimalFormat.parse(formattedNumber).doubleValue();
            System.out.println("Parsed Number: " + number);
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
    }
}

Format currency amounts:

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

public class DecimalFormatExample {
    
    
    public static void main(String[] args) {
    
    
        double amount = 12345.67;

        // 创建 NumberFormat 对象,并指定为货币格式
        NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.getDefault());

        // 将 NumberFormat 转换为 DecimalFormat,以便进一步自定义格式
        DecimalFormat decimalFormat = (DecimalFormat) currencyFormat;

        // 设置货币格式模式
        decimalFormat.applyPattern("\u00A4#,##0.00");

        // 格式化货币金额
        String formattedAmount = decimalFormat.format(amount);

        System.out.println("Formatted Amount: " + formattedAmount);
    }
}
输出(以中国人民币为例):

Formatted Amount: ¥12,345.67

Percent formatting:

import java.text.DecimalFormat;

public class DecimalFormatExample {
    
    
    public static void main(String[] args) {
    
    
        double percentage = 0.75;

        // 创建 DecimalFormat 对象,并指定百分比格式模式
        DecimalFormat decimalFormat = new DecimalFormat("0.00%");

        // 将小数转换为百分比字符串
        String formattedPercentage = decimalFormat.format(percentage);

        System.out.println("Formatted Percentage: " + formattedPercentage);
    }
}

输出:

Formatted Percentage: 75.00%

2. DateTimeFormatter class

The DateTimeFormatter class is a date and time formatting and parsing class introduced in Java 8. It provides a wealth of methods and modes for date and time formatting and parsing. The following are some common methods and application examples of the DateTimeFormatter class:
Formatting date and time:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {
    
    
    public static void main(String[] args) {
    
    
        LocalDateTime dateTime = LocalDateTime.now();

        // 创建 DateTimeFormatter 对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化日期时间
        String formattedDateTime = dateTime.format(formatter);

        System.out.println("Formatted DateTime: " + formattedDateTime);
    }
}

输出:

Formatted DateTime: 2023-06-21 15:30:45

Parse date time

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {
    
    
    public static void main(String[] args) {
    
    
        String dateTimeString = "2023-06-21 15:30:45";

        // 创建 DateTimeFormatter 对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析日期时间字符串
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);

        System.out.println("Parsed DateTime: " + dateTime);
    }
}
输出:

Parsed DateTime: 2023-06-21T15:30:45

Predefined formatters:
The DateTimeFormatter class also provides some predefined formatters that simplify date and time formatting and parsing.

For example, use the ISO_LOCAL_DATE formatter to format a date:

DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
String formattedDate = LocalDate.now().format(formatter);
System.out.println("Formatted Date: " + formattedDate);

输出:

Formatted Date: 2023-06-21

Localization settings:
The DateTimeFormatter class supports specifying different localization settings to display date times according to a specific locale.

For example, use Chinese localization to format a date:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日", Locale.CHINA);
String formattedDate = LocalDate.now().format(formatter);
System.out.println("Formatted Date: " + formattedDate);

输出:

Formatted Date: 20230621

Fourth, the calculation of numbers and dates

1.Calendar class

We can now format and create a date object, but how can we set and get specific parts of the date data, such as the hour, day, or minute? And how can we add or subtract values ​​from these parts of the date? Woolen cloth?
答案是使用Calendar 类。

The Calendar class is much more powerful than the Date class, and its implementation is also more complex than the Date class.
The Calendar class is an abstract class that implements objects of specific subclasses in actual use. The process of creating objects is transparent to programmers, and only needs to be created using the getInstance method.

Get the current datetime:

import java.util.Calendar;

public class CalendarExample {
    
    
    public static void main(String[] args) {
    
    
        // 获取当前日期时间
        Calendar calendar = Calendar.getInstance();
        System.out.println("Current date and time: " + calendar.getTime());
    }
}

输出:

Current date and time: Thu Jun 21 15:30:45 CST 2023

where the object field type

import java.util.Calendar;

public class CalendarExample {
    
    
    public static void main(String[] args) {
    
    
        // 获取年份
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        System.out.println("Year: " + year);

        // 获取月份(注意月份从 0 开始,所以需要加 1)
        int month = calendar.get(Calendar.MONTH) + 1;
        System.out.println("Month: " + month);

        // 获取日期
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println("Day of the month: " + dayOfMonth);

        // 获取小时
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        System.out.println("Hour: " + hour);

        // 获取分钟
        int minute = calendar.get(Calendar.MINUTE);
        System.out.println("Minute: " + minute);

        // 获取秒钟
        int second = calendar.get(Calendar.SECOND);
        System.out.println("Second: " + second);
    }
}


输出:

Year: 2023
Month: 6
Day of the month: 21
Hour: 15
Minute: 30
Second: 45

Set the value of a specific field:

import java.util.Calendar;

public class CalendarExample {
    
    
    public static void main(String[] args) {
    
    
        Calendar calendar = Calendar.getInstance();

        // 设置年份为 2022
        calendar.set(Calendar.YEAR, 2022);

        // 设置月份为 10(注意月份从 0 开始,所以设置为 9)
        calendar.set(Calendar.MONTH, 9);

        // 设置日期为 15
        calendar.set(Calendar.DAY_OF_MONTH, 15);

        System.out.println("Updated date and time: " + calendar.getTime());
    }
}

输出:

Updated date and time: Fri Oct 15 15:30:45 CST 2022

Date calculations and operations:

import java.util.Calendar;

public class CalendarExample {
    
    
    public static void main(String[] args) {
    
    
        Calendar calendar = Calendar.getInstance();

        // 增加一个月
        calendar.add(Calendar.MONTH, 1);

        // 减少一周
        calendar.add(Calendar.WEEK_OF_YEAR, -1);

        // 比较两个日期
        Calendar anotherCalendar = Calendar.getInstance();
        anotherCalendar.set(Calendar.YEAR, 2023);
        boolean isAfter = calendar.after(anotherCalendar);
        boolean isBefore = calendar.before(anotherCalendar);

        System.out.println("Updated date and time: " + calendar.getTime());
        System.out.println("Is after: " + isAfter);
        System.out.println("Is before: " + isBefore);
    }
}

输出:

Updated date and time: Sat Jul 15 15:30:45 CST 2023
Is after: true
Is before: false

However, the Calendar class has been deprecated in Java 8 and it is recommended to use the new date and time APIs (such as LocalDate, LocalTime and LocalDateTime) instead.

Guess you like

Origin blog.csdn.net/m0_68987535/article/details/131334504