Java에서 현재 날짜를 문자열로 변환하는 방법은 무엇입니까?
Java에서 현재 날짜를 문자열로 어떻게 변환합니까?
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
여기 에서 찍은
// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();
DateFormat
구현을 사용하십시오 . 예 : SimpleDateFormat
.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String data = df.format(new Date());
더 빠름 :
String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
tl; dr
LocalDate.now()
.toString()
2017-01-23
원하는 / 예상 시간대를 명시 적으로 지정하는 것이 좋습니다.
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.toString()
java.time
Java 8 이상에서 최신 방식은 java.time 프레임 워크를 사용하는 것입니다.
특정 시점에 날짜가 전 세계적으로 다르므로 시간대를 지정하십시오.
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ; // Or ZoneOffset.UTC or ZoneId.systemDefault()
LocalDate today = LocalDate.now( zoneId ) ;
String output = today.toString() ;
2017-01-23
기본적으로 표준 ISO 8601 형식 의 문자열을 얻습니다 .
다른 형식의 경우 java.time.format.DateTimeFormatter
클래스를 사용하십시오 .
java.time 정보
java.time의 프레임 워크는 나중에 자바 8에 내장되어 있습니다. 이 클래스는 까다로운 기존에 대신 기존 과 같은 날짜 - 시간의 수업을 java.util.Date
, Calendar
, SimpleDateFormat
.
Joda 타임 프로젝트는 지금에 유지 관리 모드 의로 마이그레이션을 조언 java.time의 클래스.
자세한 내용은 Oracle Tutorial을 참조하십시오 . 그리고 많은 예제와 설명을 위해 Stack Overflow를 검색하십시오. 사양은 JSR 310 입니다.
java.time 객체를 데이터베이스와 직접 교환 할 수 있습니다 . JDBC 4.2 이상을 준수 하는 JDBC 드라이버를 사용하십시오 . 문자열이나 클래스 가 필요하지 않습니다 .java.sql.*
java.time 클래스는 어디서 구할 수 있습니까?
- 자바 SE 8 , 자바 SE 9 , 자바 SE (10) , 그리고 나중에
- 내장.
- 번들로 구현 된 표준 Java API의 일부입니다.
- Java 9에는 몇 가지 사소한 기능과 수정 사항이 추가되었습니다.
- Java SE 6 및 Java SE 7
- java.time 기능의 대부분은 ThreeTen-Backport의 Java 6 및 7로 백 포트됩니다 .
- 기계적 인조 인간
- java.time 클래스의 최신 버전의 Android 번들 구현.
- 이전 Android (<26)의 경우 ThreeTenABP 프로젝트는 ThreeTen-Backport (위에서 언급)를 채택합니다 . 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.
Most of the answers are/were valid. The new JAVA API modification for Date handling made sure that some earlier ambiguity in java date handling is reduced.
You will get a deprecated message for similar calls.
new Date() // deprecated
The above call had the developer to assume that a new Date object will give the Date object with current timestamp. This behavior is not consistent across other Java API classes.
The new way of doing this is using the Calendar Instance.
new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()
Here too the naming convention is not perfect but this is much organised. For a person like me who has a hard time mugging up things but would never forget something if it sounds/appears logical, this is a good approach.
This is more synonymous to real life
- We get a Calendar object and we look for the time in it. ( you must be wondering no body gets time from a Calendar, that is why I said it is not perfect.But that is a different topic altogether)
- Then we want the date in a simple Text format so we use a SimpleDateFormat utility class which helps us in formatting the Date from Step 1. I have used yyyy, MM ,dd as parameters in the format. Supported date format parameters
One more way to do this is using Joda time API
new DateTime().toString("yyyy-MM-dd")
or the much obvious
new DateTime(Calendar.getInstance().getTime()).toString("yyyy-MM-dd")
both will return the same result.
For time as YYYY-MM-dd
String time = new DateTime( yourData ).toString("yyyy-MM-dd");
And the Library of DateTime is:
import org.joda.time.DateTime;
public static Date getDateByString(String dateTime) {
if(dateTime==null || dateTime.isEmpty()) {
return null;
}
else{
String modified = dateTime + ".000+0000";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date dateObj = new Date();
Date dateObj1 = new Date();
try {
if (dateTime != null) {
dateObj = formatter.parse(modified);
}
} catch (ParseException e) {
e.printStackTrace();
}
return dateObj;
}
}
참고URL : https://stackoverflow.com/questions/2942857/how-to-convert-current-date-into-string-in-java
'Programming' 카테고리의 다른 글
명령 줄의 프로세서 / 코어 수 (0) | 2020.08.08 |
---|---|
마지막 자식 선택기 사용 (0) | 2020.08.08 |
선언되지 않은 식별자 'kUTTypeMovie'사용 (0) | 2020.08.08 |
사전과 해시 테이블의 차이점 (0) | 2020.08.08 |
정의되지 않은 매크로 : AC_MSG_ERROR (0) | 2020.08.08 |