Java LocalDateTime Calculate safeCreateFromValue(LocalDateTime datetime, int year, int month, int day, int hour, int minute, int second)

Here you can find the source of safeCreateFromValue(LocalDateTime datetime, int year, int month, int day, int hour, int minute, int second)

Description

safe Create From Value

License

Open Source License

Declaration

public static LocalDateTime safeCreateFromValue(LocalDateTime datetime, int year, int month, int day, int hour,
            int minute, int second) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.time.LocalDateTime;

public class Main {
    public static LocalDateTime safeCreateFromValue(LocalDateTime datetime, int year, int month, int day, int hour,
            int minute, int second) {
        if (isValidDate(year, month, day) && isValidTime(hour, minute, second)) {
            datetime = safeCreateFromValue(datetime, year, month, day);
            datetime = datetime.plusHours(hour - datetime.getHour());
            datetime = datetime.plusMinutes((minute - datetime.getMinute()));
            datetime = datetime.plusSeconds(second - datetime.getSecond());
        }// w  w w . j  a  va  2  s .co  m

        return datetime;
    }

    public static LocalDateTime safeCreateFromValue(LocalDateTime datetime, int year, int month, int day) {
        if (isValidDate(year, month, day)) {
            datetime = datetime.plusYears(year - datetime.getYear());
            datetime = datetime.plusMonths((month - datetime.getMonthValue()));
            datetime = datetime.plusDays(day - datetime.getDayOfMonth());
        }

        return datetime;
    }

    public static Boolean isValidDate(int year, int month, int day) {
        if (year < 1 || year > 9999) {
            return false;
        }

        Integer[] validDays = { 31, year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ? 29 : 28, 31, 30, 31, 30,
                31, 31, 30, 31, 30, 31 };

        return month >= 1 && month <= 12 && day >= 1 && day <= validDays[month - 1];
    }

    public static boolean isValidTime(int hour, int minute, int second) {
        return 0 <= hour && hour <= 23 && 0 <= minute && minute <= 59 && 0 <= second && second <= 59;
    }
}

Related

  1. oldDateToISO8601LocalDateTime(Date nextColumnDate)
  2. parseStringToLocalDateTimeWithSpecifiedTime(String strDate, String time)
  3. parseTimeStamp(LocalDateTime actualDate, LocalDateTime checkedDate, boolean isDateFrom)
  4. printDateTime(LocalDateTime dateTime)
  5. relativeDateTime(final LocalDateTime contextDate, final String str, final boolean add)
  6. secondsBetween(LocalDateTime date1, LocalDateTime date2)
  7. setTime(LocalDateTime source, String time)
  8. shiftDateTime(String timex, LocalDateTime reference, boolean future)
  9. shouldSend(Optional emailSentOpt, int timeToWait)