[java] Java 문자열에서 날짜 형식 변경

나는 String데이트를 대표합니다.

String date_s = "2011-01-18 00:00:00.0";

그것을로 변환하고 형식으로 Date출력 하고 싶습니다 YYYY-MM-DD.

2011-01-18

어떻게하면 되나요?


좋아, 아래에서 검색 한 답변을 바탕으로 내가 시도한 것이 있습니다.

String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));

그러나 02011-00-1원하는 대신 출력 합니다 2011-01-18. 내가 무엇을 잘못하고 있지?



답변

특정 패턴의 a 를로 구문 분석 하려면 LocalDateTime#parse()(또는 ZonedDateTime#parse()문자열에 시간대 부분이 포함 된 경우) 사용하십시오 .StringLocalDateTime

String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));

사용 LocalDateTime#format()(또는 ZonedDateTime#format()형식으로) LocalDateTime로를 String특정 패턴으로.

String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18

또는 아직 Java 8을 사용하지 않는 경우 특정 패턴의 a SimpleDateFormat#parse()를로 구문 분석하는 데 사용 String하십시오 Date.

String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);

a를 특정 패턴 으로 SimpleDateFormat#format()형식화하는 데 사용 합니다 .DateString

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18

또한보십시오:


업데이트 : 실패한 시도에 따라 패턴은 대소 문자를 구분 합니다. 개별 부분의 약자 인 java.text.SimpleDateFormatjavadoc을 읽으십시오 . 따라서 M몇 달과 m몇 분을 의미합니다. 또한 연도는 yyyy5 자리 가 아닌 4 자리 숫자로 존재합니다 yyyyy. 위에 게시 한 코드 스 니펫을 자세히 살펴보십시오.


답변

서식은 대소 문자를 구분하므로 mm이 아닌 월 (이것은 분)이고 yyyy는 참조 용으로 다음 치트 시트를 사용할 수 있습니다.

G   Era designator  Text    AD
y   Year    Year    1996; 96
Y   Week year   Year    2009; 09
M   Month in year   Month   July; Jul; 07
w   Week in year    Number  27
W   Week in month   Number  2
D   Day in year Number  189
d   Day in month    Number  10
F   Day of week in month    Number  2
E   Day name in week    Text    Tuesday; Tue
u   Day number of week (1 = Monday, ..., 7 = Sunday)    Number  1
a   Am/pm marker    Text    PM
H   Hour in day (0-23)  Number  0
k   Hour in day (1-24)  Number  24
K   Hour in am/pm (0-11)    Number  0
h   Hour in am/pm (1-12)    Number  12
m   Minute in hour  Number  30
s   Second in minute    Number  55
S   Millisecond Number  978
z   Time zone   General time zone   Pacific Standard Time; PST; GMT-08:00
Z   Time zone   RFC 822 time zone   -0800
X   Time zone   ISO 8601 time zone  -08; -0800; -08:00

예 :

"yyyy.MM.dd G 'at' HH:mm:ss z"  2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy"  Wed, Jul 4, '01
"h:mm a"    12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa"  02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z"    Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"   2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"   2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u"  2001-W27-3


답변

대답은 물론 SimpleDateFormat 객체를 만들어 String을 Date로 구문 분석하고 Dates를 String으로 형식화하는 데 사용합니다. SimpleDateFormat을 시도했지만 작동하지 않으면 코드와 오류가 표시 될 수 있습니다.

부록 : 문자열 형식의 “mm”은 “MM”과 다릅니다. 몇 달 동안 MM을 사용하고 몇 분 동안 MM을 사용하십시오. 또한 yyyyy는 yyyy와 다릅니다. 예 :

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2011-01-18 00:00:00.0";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"  
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dt1.format(date));
    }

}


답변

단순히 이것을 사용하지 않는 이유

Date convertToDate(String receivedDate) throws ParseException{
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        Date date = formatter.parse(receivedDate);
        return date;
    }

또한 이것은 다른 방법입니다.

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String requiredDate = df.format(new Date()).toString();

또는

Date requiredDate = df.format(new Date());

건배!


답변

java.timeJava 8 이상 에서 패키지 사용 :

String date = "2011-01-18 00:00:00.0";
TemporalAccessor temporal = DateTimeFormatter
    .ofPattern("yyyy-MM-dd HH:mm:ss.S")
    .parse(date); // use parse(date, LocalDateTime::from) to get LocalDateTime
String output = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(temporal);


답변

에서 [BalusC의 수정을 포함하도록 편집] SimpleDateFormat의의 클래스는 트릭을 수행해야합니다

String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
  Date date = format.parse("2011-01-18 00:00:00.0");
  System.out.println(date);
} catch (ParseException e) {
  e.printStackTrace();
}


답변

다른 답변은 정확합니다. 기본적으로 패턴에 잘못된 “y”문자 수가 있습니다.

시간대

한가지 더 문제가 있습니다… 당신은 시간대를 다루지 않았습니다. UTC 를 의도 한 경우 그렇게 말했을 것입니다. 그렇지 않으면 답변이 완료되지 않은 것입니다. 시간이없는 날짜 부분 만 있으면 문제가 없습니다. 그러나 시간이 필요할 수있는 추가 작업을 수행하려면 시간대를 지정해야합니다.

조다 타임

다음은 동일한 종류의 코드이지만 타사 오픈 소스를 사용하는 것입니다. Joda-Time 2.3 라이브러리를 사용합니다.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

String date_s = "2011-01-18 00:00:00.0";

org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );

// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.

// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );

달릴 때…

dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18

dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z