Programing

Java로 날짜에 n 시간을 추가 하시겠습니까?

crosscheck 2020. 6. 29. 08:04
반응형

Java로 날짜에 n 시간을 추가 하시겠습니까?


Date 객체에 n 시간을 어떻게 추가합니까? StackOverflow에서 일을 사용하는 또 다른 예를 찾았지만 여전히 몇 시간 동안 수행하는 방법을 이해하지 못합니다.


캘린더 클래스를 확인하십시오. 그것은이 add시간 조작을 허용하는 방법 (일부 다른 사람을). 이와 같은 것이 작동해야합니다.

    Calendar cal = Calendar.getInstance(); // creates calendar
    cal.setTime(new Date()); // sets calendar time/date
    cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
    cal.getTime(); // returns new date object, one hour in the future

자세한 내용은 API확인하십시오 .


Apache Commons / Lang 을 사용하는 경우 다음을 사용 하여 한 번에 수행 할 수 있습니다 DateUtils.addHours().

Date newDate = DateUtils.addHours(oldDate, 3);

(원래 개체는 변경되지 않습니다)


@Christopher의 예를 단순화합니다.

상수가 있다고 가정 해보십시오.

public static final long HOUR = 3600*1000; // in milli-seconds.

당신은 쓸 수 있습니다.

Date newDate = new Date(oldDate.getTime() + 2 * HOUR);

Date 객체 대신 long사용 하여 날짜 / 시간을 저장하면 할 수 있습니다

long newDate = oldDate + 2 * HOUR;

tl; dr

myJavaUtilDate.toInstant()
              .plusHours( 8 )

또는…

myJavaUtilDate.toInstant()                // Convert from legacy class to modern class, an `Instant`, a point on the timeline in UTC with resolution of nanoseconds.
              .plus(                      // Do the math, adding a span of time to our moment, our `Instant`. 
                  Duration.ofHours( 8 )   // Specify a span of time unattached to the timeline.
               )                          // Returns another `Instant`. Using immutable objects creates a new instance while leaving the original intact.

java.time 사용

Java 8 이상에 내장 된 java.time 프레임 워크는 이전 Java.util.Date/.Calendar 클래스를 대체합니다. 그 오래된 수업은 악명 높았습니다. 피하십시오.

toInstantjava.util.Date에 새로 추가 된 메소드를 사용하여 이전 유형에서 새 java.time 유형으로 변환하십시오. Instant의 타임 라인에 순간 UTC 의 해상도를 가진 나노초 .

Instant instant = myUtilDate.toInstant();

등을 Instant전달하여 시간을 추가 할 수 있습니다 .TemporalAmountDuration

Duration duration = Duration.ofHours( 8 );
Instant instantHourLater = instant.plus( duration );

해당 날짜-시간을 읽으려면을 호출하여 표준 ISO 8601 형식의 문자열을 생성하십시오 toString.

String output = instantHourLater.toString();

일부 지역의 벽시계 시간 렌즈를 통해 그 순간을보고 싶을 수도 있습니다 . Instant을 만들어 원하는 / 예상 시간대로를 조정하십시오 ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

또는 전화 plusHours로 시간 수를 추가 할 수 있습니다. 존을 의미한다는 것은 일광 절약 시간제 (DST)를 의미하며 기타 예외는 귀하를 대신하여 처리됩니다.

ZonedDateTime later = zdt.plusHours( 8 );

당신은을 포함하여 이전 날짜 - 시간 클래스를 사용하지 말아야 java.util.Date하고 .Calendar. 그러나 java.util.Datejava.time 유형에 대해 아직 업데이트되지 않은 클래스와의 상호 운용성 이 정말로 필요한 경우 ZonedDateTimevia 에서 변환하십시오 Instant. 이전 클래스에 추가 된 새로운 메소드는 java.time 유형과의 변환을 용이하게합니다.

java.util.Date date = java.util.Date.from( later.toInstant() );

변환에 대한 자세한 설명은 참조 내 대답 , 질문에를 무엇 "java.time"유형에 java.util.Date를 변환? .


java.time에 대하여

java.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 이 클래스는 까다로운 기존에 대신 기존 과 같은 날짜 - 시간의 수업을 java.util.Date, Calendar, SimpleDateFormat.

Joda 타임 프로젝트는 지금에 유지 관리 모드 의로 마이그레이션을 조언 java.time의 클래스.

자세한 내용은 Oracle Tutorial을 참조하십시오 . 많은 예제와 설명을 보려면 스택 오버플로를 검색하십시오. 사양은 JSR 310 입니다.

java.time 객체를 데이터베이스와 직접 교환 할 수 있습니다 . JDBC 4.2 이상을 준수 하는 JDBC 드라이버를 사용하십시오 . 문자열이 필요없고 수업이 필요 없습니다 .java.sql.*

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


With Joda-Time

DateTime dt = new DateTime();
DateTime added = dt.plusHours(6);

Since Java 8:

LocalDateTime.now().minusHours(1);

See LocalDateTime API.


Something like:

Date oldDate = new Date(); // oldDate == current time
final long hoursInMillis = 60L * 60L * 1000L;
Date newDate = new Date(oldDate().getTime() + 
                        (2L * hoursInMillis)); // Adds 2 hours

Using the newish java.util.concurrent.TimeUnit class you can do it like this

    Date oldDate = new Date(); // oldDate == current time
    Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Adds 2 hours

This is another piece of code when your Date object is in Datetime format. The beauty of this code is, If you give more number of hours the date will also update accordingly.

    String myString =  "09:00 12/12/2014";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd/MM/yyyy");
    Date myDateTime = null;

    //Parse your string to SimpleDateFormat
    try
      {
        myDateTime = simpleDateFormat.parse(myString);
      }
    catch (ParseException e)
      {
         e.printStackTrace();
      }
    System.out.println("This is the Actual Date:"+myDateTime);
    Calendar cal = new GregorianCalendar();
    cal.setTime(myDateTime);

    //Adding 21 Hours to your Date
    cal.add(Calendar.HOUR_OF_DAY, 21);
    System.out.println("This is Hours Added Date:"+cal.getTime());

Here is the Output:

    This is the Actual Date:Fri Dec 12 09:00:00 EST 2014
    This is Hours Added Date:Sat Dec 13 06:00:00 EST 2014

Date argDate = new Date(); //set your date.
String argTime = "09:00"; //9 AM - 24 hour format :- Set your time.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
String dateTime = sdf.format(argDate) + " " + argTime;
Date requiredDate = dateFormat.parse(dateTime);

If you're willing to use java.time, here's a method to add ISO 8601 formatted durations:

import java.time.Duration;
import java.time.LocalDateTime;

...

LocalDateTime yourDate = ...

...

// Adds 1 hour to your date.

yourDate = yourDate.plus(Duration.parse("PT1H")); // Java.
// OR
yourDate = yourDate + Duration.parse("PT1H"); // Groovy.  

You can do it with Joda DateTime API

DateTime date= new DateTime(dateObj);
date = date.plusHours(1);
dateObj = date.toDate();

by using Java 8 classes. we can manipulate date and time very easily as below.

LocalDateTime today = LocalDateTime.now();
LocalDateTime minusHours = today.minusHours(24);
LocalDateTime minusMinutes = minusHours.minusMinutes(30);
LocalDate localDate = LocalDate.from(minusMinutes);

You can use the LocalDateTime class from Java 8. For eg :

long n = 4;
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime.plusHours(n));

You can use this method, It is easy to understand and implement :

public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
    calendar.add(Calendar.MINUTE, nombreMinute);
    calendar.add(Calendar.SECOND, nombreSeconde);
    return calendar.getTime();
}

참고URL : https://stackoverflow.com/questions/3581258/adding-n-hours-to-a-date-in-java

반응형