Programming

데이트에 하루를 추가하는 방법?

procodes 2020. 5. 9. 17:02
반응형

데이트에 하루를 추가하는 방법? [복제]


이 질문에는 이미 답변이 있습니다.

특정 날짜에 하루를 추가하고 싶습니다. 어떻게해야합니까?

Date dt = new Date();

이제이 날짜에 하루를 추가하고 싶습니다.


주어진 Date dt당신은 몇 가지 가능성이있다 :

해결 방법 1 : 다음 Calendar클래스를 사용할 수 있습니다 .

Date dt = new Date();
Calendar c = Calendar.getInstance(); 
c.setTime(dt); 
c.add(Calendar.DATE, 1);
dt = c.getTime();

해결 방법 2 : 클래스 의 다양한 단점으로 인해 Joda-Time 라이브러리 사용을 진지하게 고려해야 합니다 Date. Joda-Time을 사용하면 다음을 수행 할 수 있습니다.

Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);

해결 방법 3 : 함께 자바 (8) 당신은 또한 새로운 사용할 수있는 JSR 310 (어떤이 Joda 타임에서 영감) API를 :

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

Date에는 UNIX-epoch 이후 밀리 초를 사용하는 생성자가 있습니다. getTime ()-method는 그 값을 제공합니다. 따라서 하루에 밀리 초를 추가하면 트릭이 수행됩니다. 이러한 조작을 정기적으로 수행하려면 값의 상수를 정의하는 것이 좋습니다.

중요한 힌트 : 모든 경우에 해당되는 것은 아닙니다. 아래의 경고 의견을 읽으십시오.


상위 답변에서 언급했듯이 java 8부터 다음을 수행 할 수 있습니다.

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

그러나 이것은 때때로 DateTimeException다음과 같이 이어질 수 있습니다 :

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-11-29T03:20:10.800Z of type java.time.Instant

시간대를 간단히 전달하면이 예외를 피할 수 있습니다.

LocalDateTime.from(dt.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1);

Date 객체에 임의의 시간을 추가하는 간단한 방법을 찾았습니다.

Date d = new Date(new Date().getTime() + 86400000)

어디:

86 400 000ms = 1 Day  : 24*60*60*1000
 3 600 000ms = 1 Hour :    60*60*1000

tl; dr

LocalDate.of( 2017 , Month.JANUARY , 23 ) 
         .plusDays( 1 )

java.time

java.util.Date수업을 완전히 피하는 것이 가장 좋습니다. 그러나 그렇게해야하는 경우 번거로운 구식 레거시 날짜-시간 클래스와 최신 java.time 클래스간에 변환 할 수 있습니다. 이전 클래스에 추가 된 새로운 메소드를 살펴보십시오.

Instant

Instant클래스는에 해당 Date하는 시간에 가깝습니다 . 밀리 초 Instant동안 나노초로 해석됩니다 Date.

Instant instant = myUtilDate.toInstant() ;

이것에 하루를 추가 할 수는 있지만 UTC로 명심하십시오. 따라서 일광 절약 시간제와 같은 예외를 고려하지 않습니다. ChronoUnit수업 시간 단위를 지정하십시오 .

Instant nextDay = instant.plus( 1 , ChronoUnit.DAYS ) ;

ZonedDateTime

시간대에 정통 ZoneId하려면 a 지정하여을 가져 오십시오 ZonedDateTime. 지정 적절한 시간대 이름 의 형식 continent/region예컨대, America/Montreal, Africa/Casablanca, 또는 Pacific/Auckland. 표준 시간대 아니EST 거나 표준화되지 않았으며 고유하지 않은 3-4 문자 약어를 사용하지 마십시오 .IST

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
ZonedDateTime zdtNextDay = zdt.plusDays( 1 ) ;

하루에 추가 할 기간을으로 표시 할 수도 있습니다 Period.

Period p = Period.ofDays( 1 ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ).plus( p ) ;

다음 날의 첫 순간을 원할 수도 있습니다. 하루가 00:00:00에 시작한다고 가정하지 마십시오. 일광 절약 시간 (DST)과 같은 예외는 하루가 다른 시간 (예 : 01:00:00)에 시작될 수 있음을 의미합니다. 하자 java.time가 해당 영역에서 해당 날짜에 하루의 첫 순간을 결정합니다.

LocalDate today = LocalDate.now( z ) ;
LocalDate tomorrow = today.plus( p ) ;
ZonedDateTime zdt = tomorrow.atStartOfDay( z ) ;

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.*

java.time 클래스는 어디서 구할 수 있습니까?

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.


Update: The Joda-Time library is now in maintenance mode. The team advises migration to the java.time classes. I am leaving this section intact for history.

Joda-Time

The Joda-Time 2.3 library makes this kind of date-time work much easier. The java.util.Date class bundled with Java is notoriously troublesome, and should be avoided.

Here is some example code.

Your java.util.Date is converted to a Joda-Time DateTime object. Unlike a j.u.Date, a DateTime truly knows its assigned time zone. Time zone is crucial as adding a day to get the same wall-clock time tomorrow might mean making adjustments such as for a 23-hour or 25-hour day in the case of Daylight Saving Time (DST) here in the United States. If you specify the time zone, Joda-Time can make that kind of adjustment. After adding a day, we convert the DateTime object back into a java.util.Date object.

java.util.Date yourDate = new java.util.Date();

// Generally better to specify your time zone rather than rely on default.
org.joda.time.DateTimeZone timeZone = org.joda.time.DateTimeZone.forID( "America/Los_Angeles" );
DateTime now = new DateTime( yourDate, timeZone );
DateTime tomorrow = now.plusDays( 1 );
java.util.Date tomorrowAsJUDate = tomorrow.toDate();

Dump to console…

System.out.println( "yourDate: " + yourDate );
System.out.println( "now: " + now );
System.out.println( "tomorrow: " + tomorrow );
System.out.println( "tomorrowAsJUDate: " + tomorrowAsJUDate );

When run…

yourDate: Thu Apr 10 22:57:21 PDT 2014
now: 2014-04-10T22:57:21.535-07:00
tomorrow: 2014-04-11T22:57:21.535-07:00
tomorrowAsJUDate: Fri Apr 11 22:57:21 PDT 2014

This will increase any date by exactly one

String untildate="2011-10-08";//can take any date in current format    
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );   
Calendar cal = Calendar.getInstance();    
cal.setTime( dateFormat.parse(untildate));    
cal.add( Calendar.DATE, 1 );    
String convertedDate=dateFormat.format(cal.getTime());    
System.out.println("Date increase by one.."+convertedDate);

you can use this method after import org.apache.commons.lang.time.DateUtils:

DateUtils.addDays(new Date(), 1));

use DateTime object obj.Add to add what ever you want day hour and etc. Hope this works:)


I prefer joda for date and time arithmetics because it is much better readable:

Date tomorrow = now().plusDays(1).toDate();

Or

endOfDay(now().plus(days(1))).toDate()
startOfDay(now().plus(days(1))).toDate()

Java 8 LocalDate API

LocalDate.now().plusDays(1L);


To make it a touch less java specific, the basic principle would be to convert to some linear date format, julian days, modified julian days, seconds since some epoch, etc, add your day, and convert back.

The reason for doing this is that you farm out the "get the leap day, leap second, etc right' problem to someone who has, with some luck, not mucked this problem up.

I will caution you that getting these conversion routines right can be difficult. There are an amazing number of different ways that people mess up time, the most recent high profile example was MS's Zune. Dont' poke too much fun at MS though, it's easy to mess up. It doesn't help that there are multiple different time formats, say, TAI vs TT.


best thing to use:

      long currenTime = System.currentTimeMillis();
      long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);

Similarly, you can add MONTHS, DAYS, MINUTES etc


In very special case If you asked to do your own date class, possibly from your Computer Programming Professor; This method would do very fine job.

public void addOneDay(){
    int [] months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    day++;
    if (day> months[month-1]){
        month++;
        day = 1;
        if (month > 12){
            year++;
            month = 1;
        }
    }
}

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);

Java 1.8 version has nice update for data time API.

Here is snippet of code:

    LocalDate lastAprilDay = LocalDate.of(2014, Month.APRIL, 30);
    System.out.println("last april day: " + lastAprilDay);
    LocalDate firstMay = lastAprilDay.plusDays(1);
    System.out.println("should be first may day: " + firstMay);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
    String formatDate = formatter.format(firstMay);
    System.out.println("formatted date: " + formatDate);

Output:

last april day: 2014-04-30
should be first may day: 2014-05-01
formatted date: 01

For more info see Java documentations to this classes:


you want after days find date this code try..

public Date getToDateAfterDays(Integer day) {
        Date nowdate = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(nowdate);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }

I will show you how we can do it in Java 8. Here you go:

public class DemoDate {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Current date: " + today);

        //add 1 day to the current date
        LocalDate date1Day = today.plus(1, ChronoUnit.DAYS);
        System.out.println("Date After 1 day : " + date1Day);
    }
}

The output:

Current date: 2016-08-15
Date After 1 day : 2016-08-16

U can try java.util.Date library like this way-

int no_of_day_to_add = 1;

Date today = new Date();
Date tomorrow = new Date( today.getYear(), today.getMonth(), today.getDate() + no_of_day_to_add );

Change value of no_of_day_to_add as you want.

I have set value of no_of_day_to_add to 1 because u wanted only one day to add.

More can be found in this documentation.

참고URL : https://stackoverflow.com/questions/1005523/how-to-add-one-day-to-a-date

반응형