Get the last day timestamp in the same month for specify timestamp. - Java java.time

Java examples for java.time:Month

Description

Get the last day timestamp in the same month for specify timestamp.

Demo Code


//package com.java2s;

import java.time.*;

public class Main {
    /**/*  w  w  w.  ja  v a  2 s  .  c  o  m*/
     * Get the last day timestamp in the same month for specify timestamp. That
     * mean the result is the last Mills second in the specify month.
     * 
     * @param timestamp
     *          A timestamp need to calcute.
     * @return
     */
    public static long getMonthTailMills(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZonedDateTime dateTime = ZonedDateTime.ofInstant(instant,
                ZoneId.systemDefault());
        // Get the last day of this month. Not use Math.pow(10, 9) to calculate the
        // max nano second
        // in consideration of performance.
        ZonedDateTime lastDateTime = ZonedDateTime.of(
                dateTime.getYear(),
                dateTime.getMonthValue(),
                dateTime.getMonth().length(
                        dateTime.toLocalDate().isLeapYear()), 23, 59, 59,
                1000000000 - 1, ZoneId.systemDefault());
        return lastDateTime.toInstant().toEpochMilli();
    }
}

Related Tutorials