2013-10-10 6 views
-1

나는 값 목록 12012, 112013, 52005을 문자열로 저장하고 있습니다. 따라서 해당 문자열을 2012 년 1 월, 2013 년 11 월, 5 월 2005 년 5 월로 변환해야합니다. 문자열을 구문 분석하고 if 문을 사용하여이 작업을 수행하는 방법을 알고 있습니다. 어떤 효율적인 방법이 있습니까? 이 같은Java에서 숫자 값을 날짜로 변환하는 방법은 무엇입니까?

+6

'SimpleDateFormat'을 확인하십시오. –

+1

가능한 [날짜 문자열을 날짜 또는 달력 객체로 변환하는 방법?] (http://stackoverflow.com/questions/43802/how-to-convert-a-date-string-to-a-date- or-calendar-object) –

+1

https://google.com/search?q=java+convert+string+to+date에 첫 번째 조회수가 있습니다. http://stackoverflow.com/questions/4216745/java-string-to- 날짜 변환 – BalusC

답변

2

당신이 나타내는 문자열을 가지고 : 간단한 코드 다음 시도 시간대없는 날짜

Calendar cal = Calendar.getInstance().clear(); 
cal.set(year, month-1, 1); 

Date date = cal.getTime(); 

또는 Joda 시간 SimpleDateFormat과 같이 Myyyy와 MMyyyy의 두 가지 형식을 가진 날짜 if 문을 피할 수 있을지 확신하지 못합니다. 그 이유는 다음과 같습니다.

SimpleDateFormat sdf1 = new SimpleDateFormat("Myyyy"); 
    SimpleDateFormat sdf2 = new SimpleDateFormat("MMyyyy"); 
    Date d = null; 
    if(5 == s.length()){ 
     d = sdf1.parse(s); 
    }else if(6 == s.length()){ 
     d = sdf2.parse(s); 
    } 
4

뭔가 작동 할 수 있습니다 : 당신이 자바 Date 또는 Calendar 또는 무엇을할지 모르는

String val = "12012"; 
int numVal = Integer.parseInt(val); 
int year = numVal % 10000; 
int month = numVal/10000; 
... create a date from that ... 

. 당신은 쉽게 그렇게 할 수 SimpleDateFormat의 패턴을 사용하여

LocalDate dt = new LocalDate(year, month, 1); 
3

가 :

String str="12012";//112013 , 52005 
SimpleDateFormat format=new SimpleDateFormat("Myyyy"); 
SimpleDateFormat resFormat=new SimpleDateFormat("MMM yyyy"); 
Date date=format.parse(str); 
System.out.println(resFormat.format(date)); 
+0

예제 Myyyy 및 MMyyyy 예제에서 주어진 두 가지 유형의 날짜가 있으므로 112013을 사용하여 솔루션을 테스트하면이 방법이 작동하는지 확신 할 수 없습니다. jan. 2013 년 11 월 대신 12013 –

관련 문제