📜  Java8 OffsetDateTime类

📅  最后修改于: 2020-10-01 06:37:30             🧑  作者: Mango

Java OffsetDateTime类

Java OffsetDateTime类是带有偏移量的日期时间的不可变表示形式。它继承了Object类并实现Comparable接口。

OffsetDateTime类用于存储日期和时间字段,精度为纳秒。

Java OffsetDateTime类声明

让我们看看java.time.OffsetDateTime类的声明。

public final class OffsetDateTime extends Object 
implements Temporal, TemporalAdjuster, Comparable, Serializable

Java OffsetDateTime的方法

Method Description
int get(TemporalField field) It is used to get the value of the specified field from this date-time as an int.
int getDayOfMonth() It is used to get the day-of-month field.
iint getDayOfYear() It is used to get the day-of-year field.
DayOfWeek getDayOfWeek() It is used to get the day-of-week field, which is an enum DayOfWeek.
OffsetDateTime minusDays(long days) It is used to return a copy of this OffsetDateTime with the specified number of days subtracted.
static OffsetDateTimenow() It is used to obtain the current date-time from the system clock in the default time-zone.
OffsetDateTime plusDays(long days) It is used to return a copy of this OffsetDateTime with the specified number of days added.
LocalDate toLocalDate() It is used to get the LocalDate part of this date-time.

Java OffsetDateTime类示例:getDayOfMonth()

import java.time.OffsetDateTime;
public class OffsetDateTimeExample1 {
public static void main(String[] args) {
OffsetDateTime offsetDT = OffsetDateTime.now();
System.out.println(offsetDT.getDayOfMonth());
}
}

输出:

18

Java OffsetDateTime类示例:getDayOfYear()

import java.time.OffsetDateTime;
public class OffsetDateTimeExample2 {
public static void main(String[] args) {
OffsetDateTime offsetDT = OffsetDateTime.now();
System.out.println(offsetDT.getDayOfYear());
}
}

输出:

18

Java OffsetDateTime类示例:getDayOfWeek()

import java.time.OffsetDateTime;
public class OffsetDateTimeExample3 {
public static void main(String[] args) {
OffsetDateTime offsetDT = OffsetDateTime.now();
System.out.println(offsetDT.getDayOfWeek());
}
}

输出:

WEDNESDAY

Java OffsetDateTime类示例:toLocalDate()

import java.time.OffsetDateTime;
public class OffsetDateTimeExample4 {
public static void main(String[] args) {
OffsetDateTime offsetDT = OffsetDateTime.now();
System.out.println(offsetDT.toLocalDate());
}
}

输出:

2017-01-18

Java OffsetDateTime类示例:minusDays()

import java.time.OffsetDateTime;
public class OffsetDateTimeExample5 {
  public static void main(String[] args) {
    OffsetDateTime offset = OffsetDateTime.now();
    OffsetDateTime value =  offset.minusDays(240);
    System.out.println(value);
  }
}

输出:

2016-05-23T12:12:31.642+05:30

Java OffsetDateTime类示例:plusDays()

import java.time.OffsetDateTime;
public class OffsetDateTimeExample6 {
  public static void main(String[] args) {
    OffsetDateTime offset = OffsetDateTime.now();
    OffsetDateTime value =  offset.plusDays(240);
    System.out.println(value);
  }
}

输出:

2017-09-15T13:50:30.526+05:30