날짜 유형 소개 - 1

"안녕하세요, 아미고. Date라는 흥미로운 유형에 대해 말씀드리고 싶습니다. 이 유형은 날짜와 시간을 저장하고 시간 간격도 측정할 수 있습니다."

"흥미롭게 들리네요. 계속하세요."

"모든 Date 객체는 1970년 1월 1일 GMT 이후의 시간을 다소 흥미로운 형식으로 저장합니다."

"워!"

"예. 이 숫자는 너무 커서 int 에 저장할 공간이 부족해서 long 에 저장해야 합니다 . 하지만 두 날짜 사이의 차이를 계산하는 데 정말 편리합니다. 밀리초 단위의 정확도를 제공합니다. 또한 날짜 변경선과 일광 절약 시간제 문제도 해결합니다."

"가장 흥미로운 부분은 각 객체가 생성 시 현재 시간으로 초기화된다는 것입니다. 현재 시간을 알려면 Date 객체를 생성하기만 하면 됩니다."

"어떻게 작업합니까?"

"여기 몇 가지 예가 있어요:"

현재 날짜 가져오기:
public static void main(String[] args) throws Exception
{
     Date today = new Date();
     System.out.println("Current date: " + today);
}
두 날짜의 차이 계산
public static void main(String[] args) throws Exception
{
    Date currentTime = new Date();           // Get the current date and time
    Thread.sleep(3000);                      // Wait 3 seconds (3000 milliseconds)
    Date newTime = new Date();               // Get the new current time

    long msDelay = newTime.getTime() - currentTime.getTime(); // Calculate the difference
    System.out.println("Time difference is: " + msDelay + " in ms");
}
일정 시간이 경과했는지 확인:
public static void main(String[] args) throws Exception
{
    Date startTime = new Date();

    long endTime = startTime.getTime() + 5000;  //    +5 seconds
    Date endDate = new Date(endTime);

    Thread.sleep(3000);              // Wait 3 seconds

    Date currentTime = new Date();
    if(currentTime.after(endDate))// Check whether currentTime is after endDate
    {
        System.out.println("End time!");
    }
}
하루가 시작된 후 경과된 시간을 확인합니다.
public static void main(String[] args) throws Exception
{
    Date currentTime = new Date();
    int hours = currentTime.getHours();
    int mins = currentTime.getMinutes();
    int secs = currentTime.getSeconds();

    System.out.println("Time since midnight " + hours + ":" + mins + ":" + secs);
}
연초부터 몇 일이 지났는지 확인합니다.
public static void main(String[] args) throws Exception
{
    Date yearStartTime = new Date();
    yearStartTime.setHours(0);
    yearStartTime.setMinutes(0);
    yearStartTime.setSeconds(0);

    yearStartTime.setDate(1);      // First day of the month
    yearStartTime.setMonth(0);     // January (the months are indexed from 0 to 11)

    Date currentTime = new Date();
    long msTimeDifference = currentTime.getTime() - yearStartTime.getTime();
    long msDay = 24 * 60 * 60 * 1000;  // The number of milliseconds in 24 hours

    int dayCount = (int) (msTimeDifference/msDay); // The number of full days
    System.out.println("Days since the start of the year: " + dayCount);
}
2
과제
Java Syntax,  레벨 8레슨 4
잠금
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

"이 getTime()메서드는 Date 개체에 저장된 밀리초 수를 반환합니다."

" after()메소드는 메서드를 호출한 날짜가 메서드에 전달된 날짜 이후 인지 확인합니다."

" getHours(), getMinutes(), getSeconds()메서드는 호출된 개체에 대해 각각 시간, 분, 초를 반환합니다."

"또한 마지막 예에서 Date 객체 에 저장된 날짜/시간을 변경할 수 있음을 알 수 있습니다 . 현재 시간과 날짜를 가져온 다음 시, 분, 초를 0으로 재설정합니다. 또한 1월을 월과 1은 일입니다. 따라서 yearStartTime객체는 현재 연도의 1월 1일 날짜와 시간 00:00:00을 저장합니다."

"그 후 다시 현재 날짜( )를 가져오고 currentTime두 날짜 간의 차이를 밀리초 단위로 계산하여 에 저장합니다 msTimeDifference."

"그런 다음 msTimeDifference24시간의 밀리초 수로 나누어 현재 연도 시작부터 오늘까지의 전체 날짜 수를 얻습니다."

"와우! 정말 멋지다!"