文章目录
一、日期转换为数字
1. Date
Date 是 Java 标准库中的一个类,提供了处理日期和时间的功能。
getTime(): 返回自 1970 年 1 月 1 日 00:00:00 GMT 起到此 Date 对象表示的日期和时间之间的毫秒数。
Date date = new Date();
long timestamp = date.getTime();
toString(): 将 Date 对象转换为字符串,格式为 EEE MMM dd HH:mm:ss zzz yyyy。
Date date = new Date();
String dateString = date.toString();
Mon May 04 09:51:52 CDT 2013
获取当前日期和时间:
Date currentDate = new Date();
System.out.println("Current Date and Time: " + currentDate);
比较日期
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.");
}
格式化日期
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(date);
System.out.println("Formatted Date: " + formattedDate);
2. LocalDate
LocalDate 是 Java 8 引入的日期类,属于 java.time 包下的一部分。它用于表示不带时间的日期,并提供了丰富的方法来进行日期的计算、格式化和操作。
以下是 LocalDate 类的一些常用方法以及应用示例:
LocalDate.now(): 获取当前日期
LocalDate currentDate = LocalDate.now();
LocalDate.of(int year, int month, int dayOfMonth):根据指定的年、月、日构造一个 LocalDate 对象。
LocalDate date = LocalDate.of(2023, 6, 21);
getYear()、getMonthValue()、getDayOfMonth(): 获取年、月、日的值。
int year = date.getYear();
int month = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();
plusXxx(long amountToAdd)、minusXxx(long amountToSubtract): 对日期进行加减操作,例如增加/减少天数、月数等
LocalDate newDate = date.plusDays(7); // 增加7天
LocalDate previousDate = date.minusMonths(1); // 减少1个月
isBefore(LocalDate other)、isAfter(LocalDate other): 判断日期的先后顺序。
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): 判断两个日期是否相等。
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(): 将 LocalDate 对象转换为字符串,格式为 yyyy-MM-dd
LocalDate date = LocalDate.now();
String dateString = date.toString();
获取当前日期:
LocalDate currentDate = LocalDate.now();
System.out.println("Current Date: " + currentDate);
计算日期差:
LocalDate date1 = LocalDate.of(2023, 6, 21);
LocalDate date2 = LocalDate.of(2023, 6,
二、数字转换为日期
1. Instant
Instant 类提供了处理精确时间点的功能,可以获得当前时间点、创建指定时间点的对象,并对时间点进行比较、计算和格式化等操作
以下是 Instant 类的一些常用方法以及应用示例:
now():
Instant now = Instant.now();
ofEpochSecond(long epochSecond): 根据指定的秒数创建一个 Instant 对象。
Instant instant = Instant.ofEpochSecond(1624264800L);
ofEpochMilli(long epochMilli): 根据指定的毫秒数创建一个 Instant 对象。
Instant instant = Instant.ofEpochMilli(1624264800000L);
getEpochSecond(): 获取从纪元开始的秒数。
long epochSecond = instant.getEpochSecond();
toEpochMilli(): 获取从纪元开始的毫秒数。
long epochMilli = instant.toEpochMilli();
isBefore(Instant other): 判断当前时间点是否在另一个时间点之前。
Instant instant1 = Instant.now();
Instant instant2 = Instant.parse("2023-06-21T12:00:00Z");
if (instant1.isBefore(instant2)) {
System.out.println("instant1 is before instant2.");
}
计算时间差:
Instant start = Instant.now();
// 执行一些耗时的操作
Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("Time taken: " + duration.getSeconds() + " seconds");
格式化时间:
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);
三、格式化数字或日期
1.DecimalFormat类
DecimalFormat(String pattern): 根据指定的模式创建一个 DecimalFormat 对象。
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) 将给定的字符串解析为数值。
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();
}
}
}
格式化货币金额:
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
百分比格式化:
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类
DateTimeFormatter 类是 Java 8 引入的日期时间格式化和解析类,它提供了丰富的方法和模式来进行日期时间的格式化和解析。下面是 DateTimeFormatter 类的一些常用方法和应用示例:
格式化日期时间:
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
解析日期时间
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
预定义的格式器:
DateTimeFormatter 类还提供了一些预定义的格式器,可以简化日期时间的格式化和解析。
例如,使用 ISO_LOCAL_DATE 格式器来格式化日期:
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
String formattedDate = LocalDate.now().format(formatter);
System.out.println("Formatted Date: " + formattedDate);
输出:
Formatted Date: 2023-06-21
本地化设置:
DateTimeFormatter 类支持指定不同的本地化设置,以根据特定的语言环境显示日期时间。
例如,使用中文本地化设置来格式化日期:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日", Locale.CHINA);
String formattedDate = LocalDate.now().format(formatter);
System.out.println("Formatted Date: " + formattedDate);
输出:
Formatted Date: 2023年06月21日
四、数字与日期的计算
1.Calendar类
我们现在已经能够格式化并创建一个日期对象了,但是我们如何才能设置和获取日期数据的特定部分呢,比如说小时,日,或者分钟? 我们又如何在日期的这些部分加上或者减去值呢?
答案是使用Calendar 类。
Calendar类的功能要比Date类强大很多,而且在实现方式上也比Date类要复杂一些。
Calendar类是一个抽象类,在实际使用时实现特定的子类的对象,创建对象的过程对程序员来说是透明的,只需要使用getInstance方法创建即可。
获取当前日期时间:
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
其中该对象字段类型
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
设置特定字段的值:
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
日期计算和操作:
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
然而,Calendar 类在 Java 8 中已被废弃,推荐使用新的日期和时间 API(例如 LocalDate、LocalTime 和 LocalDateTime)来替代。