2024年3月30日发(作者:)

JAVA处理日期时间常用方法

1. Date类:在包中,Date类表示特定的瞬间,使用当前

时刻创建一个Date对象,可以使用无参构造函数Date(或者

tTimeMillis(方法。

```java

import ;

public class DateExample

public static void main(String[] args)

Date now = new Date(; // 当前时间

n(now);

}

```

输出结果为:Wed Oct 20 09:38:45 CST 2024

2. Calendar类:在包中,Calendar类是一个抽象基类,

用于获取并操作日历字段,可以进行日期和时间的加、减、格式化等操作。

```java

import ar;

public class CalendarExample

public static void main(String[] args)

Calendar cal = tance(;

int year = ();

int month = () + 1; // 月份从0开始,需

要加1

int day = (_OF_MONTH);

int hour = (_OF_DAY);

int minute = ();

int second = ();

n(year + "-" + month + "-" + day + " " +

hour + ":" + minute + ":" + second);

}

```

输出结果为:2024-10-209:38:45

3. SimpleDateFormat类:在包中,SimpleDateFormat类

用于将日期格式化为指定的模式。

```java

import DateFormat;

import ;

public class SimpleDateFormatExample

public static void main(String[] args)

Date now = new Date(;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd

HH:mm:ss");

String formattedDate = (now);

n(formattedDate);

}

```

输出结果为:2024-10-2009:38:45

```java

public class LocalDateExample

public static void main(String[] args)

LocalDate today = (; // 当前日期

int year = r(;

int month = thValue(;

int day = OfMonth(;

n(year + "-" + month + "-" + day);

}

```

输出结果为:2024-10-20。

```java

public class LocalTimeExample

public static void main(String[] args)

LocalTime now = (; // 当前时间

int hour = r(;

int minute = ute(;

int second = ond(;

n(hour + ":" + minute + ":" + second);

}

```

输出结果为:9:38:45

```java

public class LocalDateTimeExample

public static void main(String[] args)

LocalDateTime now = (; // 当前日期时间

int year = r(;

int month = thValue(;

int day = OfMonth(;

int hour = r(;

int minute = ute(;

int second = ond(;

n(year + "-" + month + "-" + day + " " +

hour + ":" + minute + ":" + second);

}

```

输出结果为:2024-10-209:38:45

除了以上常用的类和方法外,还可以使用ZonedDateTime类进行时区

的处理,Duration类进行时间间隔的计算,Period类进行日期间隔的计

算等。

总结:Java中处理日期和时间的常用类有Date、Calendar、

SimpleDateFormat、LocalDate、LocalTime、LocalDateTime等,可以根

据需求选择合适的类和方法来进行日期和时间的处理。