자바 날짜를 한 시간 뒤로 변경
Java 날짜 개체가 있습니다.
Date currentDate = new Date();
이것은 현재 날짜와 시간을 제공합니다. 예:
Thu Jan 12 10:17:47 GMT 2012
대신 날짜를 가져 와서 한 시간 뒤로 변경하여 다음을 제공해야합니다.
Thu Jan 12 09:17:47 GMT 2012
이를 수행하는 가장 좋은 방법은 무엇입니까?
java.util.Calendar
Calendar cal = Calendar.getInstance();
// remove next line if you're always using the current time.
cal.setTime(currentDate);
cal.add(Calendar.HOUR, -1);
Date oneHourBack = cal.getTime();
java.util.Date
new Date(System.currentTimeMillis() - 3600 * 1000);
org.joda.time.LocalDateTime
new LocalDateTime().minusHours(1)
자바 8 : java.time.LocalDateTime
LocalDateTime.now().minusHours(1)
자바 8 java.time.Instant
// always in UTC if not timezone set
Instant.now().minus(1, ChronoUnit.HOURS));
// with timezone, Europe/Berlin for example
Instant.now()
.atZone(ZoneId.of("Europe/Berlin"))
.minusHours(1));
@Sumit Jain의 솔루션과 유사
Date currentDate = new Date(System.currentTimeMillis() - 3600 * 1000);
또는
Date currentDate = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1));
tl; dr
에서 UTC :
Instant.now().minus( 1 , ChronoUnit.HOURS )
또는 구역화 :
Instant.now()
.atZone( ZoneId.of ( "America/Montreal" ) )
.minusHours( 1 )
java.time 사용
Java 8 이상에는 새로운 java.time 프레임 워크가 내장되어 있습니다.
Instant
UTC (GMT)에만 관심이 있다면 Instant
클래스 를 사용하십시오 .
Instant instant = Instant.now ();
Instant instantHourEarlier = instant.minus ( 1 , ChronoUnit.HOURS );
콘솔에 덤프합니다.
System.out.println ( "instant: " + instant + " | instantHourEarlier: " + instantHourEarlier );
인스턴트 : 2015-10-29T00 : 37 : 48.921Z | instantHourEarlier : 2015-10-28T23 : 37 : 48.921Z
이 순간에 어제 날짜로 건너 뛰는 방법에 유의하십시오.
ZonedDateTime
시간대에 관심이 있다면 ZonedDateTime
수업을 사용하십시오 . 인스턴트로 시작하여 시간대, ZoneId
객체를 할당 할 수 있습니다 . 이 클래스는 일광 절약 시간 (DST) 과 같은 이상 항목에 필요한 조정을 처리합니다 .
Instant instant = Instant.now ();
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
ZonedDateTime zdtHourEarlier = zdt.minus ( 1 , ChronoUnit.HOURS );
콘솔에 덤프합니다.
System.out.println ( "instant: " + instant + "\nzdt: " + zdt + "\nzdtHourEarlier: " + zdtHourEarlier );
즉시 : 2015-10-29T00 : 50 : 30.778Z
zdt : 2015-10-28T20 : 50 : 30.778-04 : 00 [미주 / 몬트리올]
zdtHourEarlier : 2015-10-28T19 : 50 : 30.778-04 : 00 [미주 / 몬트리올]
변환
이전 java.util.Date/.Calendar 클래스는 이제 구식입니다. 그들을 피하십시오. 그들은 악명 높고 혼란 스럽습니다.
java.time 유형에 대해 아직 업데이트되지 않은 이전 코드로 작동하기 위해 이전 클래스를 사용해야하는 경우 변환 메소드를 호출하십시오. 다음은 Instant 또는 ZonedDateTime에서 java.util.Date로 이동하는 예제 코드입니다.
java.util.Date date = java.util.Date.from( instant );
…또는…
java.util.Date date = java.util.Date.from( zdt.toInstant() );
java.time 정보
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
Use Calendar.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) - 1);
Or using the famous Joda Time library:
DateTime dateTime = new DateTime();
dateTime = dateTime.minusHours(1);
Date modifiedDate = dateTime.toDate();
Just subtract the number of milliseconds in an hour from the date.
currentDate.setTime(currentDate.getTime() - 3600 * 1000));
You can use from bellow code for date and time :
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println("Add one day to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
System.out.println("Add one month to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 1);
System.out.println("Add one year to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.HOUR, 1);
System.out.println("Add one hour to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 1);
System.out.println("Add one minute to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 1);
System.out.println("Add one second to current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println("Subtract one day from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println("Subtract one month from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
System.out.println("Subtract one year from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);
System.out.println("Subtract one hour from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -1);
System.out.println("Subtract one minute from current date : " + dateFormat.format(cal.getTime()));
cal = Calendar.getInstance();
cal.add(Calendar.SECOND, -1);
System.out.println("Subtract one second from current date : " + dateFormat.format(cal.getTime()));
Output :
Current Date Time : 2008/12/28 10:24:53
Add one day to current date : 2008/12/29 10:24:53
Add one month to current date : 2009/01/28 10:24:53
Add one year to current date : 2009/12/28 10:24:53
Add one hour to current date : 2008/12/28 11:24:53
Add one minute to current date : 2008/12/28 10:25:53
Add one second to current date : 2008/12/28 10:24:54
Subtract one day from current date : 2008/12/27 10:24:53
Subtract one month from current date : 2008/11/28 10:24:53
Subtract one year from current date : 2007/12/28 10:24:53
Subtract one hour from current date : 2008/12/28 09:24:53
Subtract one minute from current date : 2008/12/28 10:23:53
Subtract one second from current date : 2008/12/28 10:24:52
This link is good : See here
And see : See too
And : Here
And : Here
And : Here
If you need just time :
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
This can be achieved using java.util.Date
. The following code will subtract 1 hour from your date.
Date date = new Date(yourdate in date format);
Date newDate = DateUtils.addHours(date, -1)
Similarly for subtracting 20 seconds from your date
newDate = DateUtils.addSeconds(date, -20)
It worked for me instead using format .To work with time just use parse and toString() methods
String localTime="6:11"; LocalTime localTime = LocalTime.parse(localtime)
LocalTime lt = 6:11; localTime = lt.toString()
Get the time in milliseconds, minus your minutes in milliseconds and convert it to Date. Here you need to objectify one!!!
int minutes = 60;
long currentDateTime = System.currentTimeMillis();
Date currentDate = new Date(currentDateTime - minutes*60*1000);
System.out.println(currentDate);
참고URL : https://stackoverflow.com/questions/8833399/changing-java-date-one-hour-back
'code' 카테고리의 다른 글
요청이 asp.net mvc에서 ajax인지 확인하는 방법은 무엇입니까? (0) | 2020.08.14 |
---|---|
PHP 다차원 배열 검색 (특정 값으로 키 찾기) (0) | 2020.08.14 |
JavaScript를 사용하여 스타일 -webkit-transform을 동적으로 설정하는 방법은 무엇입니까? (0) | 2020.08.14 |
AngularJS에서 $ rootScope. $ broadcast를 사용하는 이유는 무엇입니까? (0) | 2020.08.14 |
포스트 빌드가 코드 1로 종료되었습니다. (0) | 2020.08.14 |