欢迎访问宙启技术站
智能推送

Java日期函数介绍

发布时间:2023-07-31 23:53:36

Java中提供了丰富的日期函数,用于处理和操作日期。下面将介绍Java中常用的日期函数。

1. Date类:

Date类是Java中处理日期和时间的类,它提供了获取当前日期、获取年、月、日、小时、分钟和秒等方法。

Date date = new Date();
int year = date.getYear() + 1900;
int month = date.getMonth() + 1;
int day = date.getDate();
int hour = date.getHours();
int minute = date.getMinutes();
int second = date.getSeconds();

2. SimpleDateFormat类:

SimpleDateFormat类用于格式化日期,可以将日期对象转换为指定格式的字符串,也可以将字符串解析为日期对象。

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

String str = "2022-01-01 12:00:00";
Date parse = sdf.parse(str);
System.out.println(parse);

3. Calendar类:

Calendar类是一个抽象类,提供了日期和时间的计算功能。它可以获取当前日期、获取年、月、日、小时、分钟和秒等方法。

Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

calendar.add(Calendar.DAY_OF_MONTH, -1);
Date date = calendar.getTime();

4. LocalDateTime类:

LocalDateTime类是Java 8中引入的日期时间类,用于替代Date和Calendar类。它提供了更方便和强大的日期时间操作方法。

LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonth().getValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();

LocalDateTime tomorrow = now.plusDays(1);

5. Duration类和Period类:

Duration类用于表示两个时间点之间的持续时间,可以获取它们之间的秒数、分钟数、小时数等。Period类用于表示两个日期之间的时长,可以获取它们之间的年数、月数、天数等。

LocalDateTime start = LocalDateTime.of(2022, 1, 1, 0, 0);
LocalDateTime end = LocalDateTime.of(2022, 1, 2, 12, 0);
Duration duration = Duration.between(start, end);
long hours = duration.toHours();

LocalDate startDate = LocalDate.of(2022, 1, 1);
LocalDate endDate = LocalDate.of(2022, 1, 7);
Period period = Period.between(startDate, endDate);
int days = period.getDays();

以上就是Java中常用的日期函数介绍,可以根据实际需求选择合适的日期函数来处理和操作日期。