java獲取時間戳精確到微秒講解「java獲取時間戳精確到毫秒」

當前時間加上時間戳

關於日期的計算,很多朋友們都喜歡用時間戳來直接相加,比如希望得到當前時間之後30天的時間,會這麼寫代碼: 直接把 new Data().getTime() 方法得到的時間戳加上30天對應的毫秒數,也就是30天 * 24小時 * 3600秒 * 1000毫秒

        Date today = new Date();
        Date nextMonth = new Date(today.getTime()+30*24*3600*1000);
        System.out.println(today);
        System.out.println(nextMonth);

得到的結果可能會讓我失敗:

Sat Jul 10 07:41:30 CST 2021
Sun Jun 20 14:38:43 CST 2021

得到的日期竟然比當前的日期還好早,你說怎麼回事呢?
原因是:
因為 int 發生了溢出

怎樣修改呢?我們只要把 30改成30L即可,讓其成為long

        Date today = new Date();
        Date nextMonth = new Date(today.getTime()+30L*24*3600*1000);
        System.out.println(today);
        System.out.println(nextMonth);

結果:

Sat Jul 10 07:44:38 CST 2021
Mon Aug 09 07:44:38 CST 2021

使用Calendar

在java8之前,我們一般使用Calendar類來實現

        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        System.out.println(c.getTime());
        c.add(Calendar.DAY_OF_MONTH,30);
        System.out.println(c.getTime());

結果:

Sat Jul 10 07:47:25 CST 2021
Mon Aug 09 07:47:25 CST 2021

java 8 日期時間

使用 Java 8 的日期時間類型,可以直接進行各種計算,更加簡潔和方便:

 LocalDateTime localDateTime = LocalDateTime.now();
 System.out.println(localDateTime.plusDays(30));

下面介紹LocalDateTime的基本用法:

1) 獲取一年、月、日

  private LocalDateTime localDateTime = null;
    @Before
    public void init(){
        localDateTime = LocalDateTime.now();
    }
    @Test
    public void test1(){
        System.out.println("Year:"+localDateTime.getYear());
        System.out.println("Month:"+localDateTime.getMonth().getValue());
        System.out.println("Day of Month:"+localDateTime.getDayOfMonth());
        System.out.println("Day of Week:"+ localDateTime.getDayOfWeek());
        System.out.println("Day of Year:"+localDateTime.getDayOfYear());
    }

結果:

Year:2021
Month:7
Day of Month:10
Day of Week:SATURDAY
Day of Year:191  
  1. 獲取小時、分鐘、秒
 System.out.println("Hour:"+localDateTime.getHour());
 System.out.println("Minute :"+localDateTime.getMinute());
 System.out.println("Second:"+localDateTime.getSecond());
 System.out.println("Nano:"+localDateTime.getNano());

結果:

Hour:8
Minute :17
Second:32
Nano:50000000
  1. 對日期做加減

可以使用各種 minus 和 plus 方法直接對日期進行加減操作,比如如下代碼實現了減一天和加一天,以及減一個月和加一個月

        System.out.println("minus days:"+ localDateTime.minusDays(1));
        System.out.println("minus months:"+localDateTime.minusMonths(1));
        System.out.println("minus year: "+localDateTime.minusYears(1));
        System.out.println("minus Hours:"+localDateTime.minusHours(1));
        System.out.println("minus seconds:"+localDateTime.minusSeconds(1));
  1. 時間的比較

LocalDateTime 類提供以下API比較LocalDateTime 對象在Java中。

  • boolean isAfter(ChronoLocalDateTime other):檢查此日期時間是否在指定日期時間之後。
  • boolean isBefore(ChronoLocalDateTime other)
  • boolean isEqual(ChronoLocalDateTime other)
  • int compareTo(ChronoLocalDateTime other) 將此日期時間與其他日期時間進行比較。
 LocalDateTime dateTime1 = LocalDateTime.of(2021,5,7,9,22,22);
      LocalDateTime dateTime2 = LocalDateTime.of(2021,6,7,9,22,22);
      LocalDateTime dateTime3 = LocalDateTime.of(2021,5,7,9,22,22);

      if(dateTime1.isBefore(dateTime2)){
          System.out.println("dateTime1 is  before dateTime2");
      }

        if(dateTime2.isAfter(dateTime3)){
            System.out.println("dateTime2 is  after dateTime3");
        }

        if(dateTime1.equals(dateTime3)){
            System.out.println("dateTime1 is equal to dateTime3");
        }

        if(dateTime1.compareTo(dateTime3) ==0){
            System.out.println("dateTime1 is equal to dateTime3");
        }
  1. 通過 with 方法進行快捷時間調節
  • 使用 TemporalAdjusters.firstDayOfMonth 得到當前月的第一天;
  • 使用 TemporalAdjusters.firstDayOfYear() 得到當前年的第一天;
  • 使用 TemporalAdjusters.previous(DayOfWeek.SATURDAY) 得到上一個周六;
  • 使用 TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY) 得到本月最後一個周五。
        System.out.println("//本月的第一天");
        System.out.println(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()));
        System.out.println("//今年的程序員日");
        System.out.println(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()).plusDays(255));
        System.out.println("//今天之前的一個周六");
        System.out.println(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.SATURDAY)));
        System.out.println("//本月最後一個工作日");
        System.out.println(LocalDate.now().with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY)));
  1. 可以直接使用 lanbda 表達式進行自定義的時間調整
 System.out.println(LocalDate.now().with(temporal -> temporal.plus(ThreadLocalRandom.current().nextInt(100), ChronoUnit.DAYS)));

除了計算外,還可以判斷日期是否符合某個條件。比如,自定義函數,判斷指定日期是否是家庭成員的生日:

public class DateTimeTest {
    private static LocalDateTime localDateTime = LocalDateTime.now();

    public static void main(String[] args) {
        System.out.println(isFamilyBirthday(localDateTime));
    }
    public static Boolean isFamilyBirthday(LocalDateTime date) {
        int month = date.getMonthValue();
        int day = date.getDayOfMonth();
        if (month == Month.JULY.getValue() && day == 10)
            return Boolean.TRUE;
        if (month == Month.SEPTEMBER.getValue() && day == 21)
            return Boolean.TRUE;
        if (month == Month.MAY.getValue() && day == 22)
            return Boolean.TRUE;
        return Boolean.FALSE;
    }
}

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/209167.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-08 15:25
下一篇 2024-12-08 15:25

相關推薦

發表回復

登錄後才能評論