developer tip

java.util.Date 형식 변환 yyyy-mm-dd에서 mm-dd-yyyy로

copycodes 2020. 11. 3. 08:16
반응형

java.util.Date 형식 변환 yyyy-mm-dd에서 mm-dd-yyyy로


나는 java.util.Date형식이 yyyy-mm-dd있습니다. 나는 그것을 형식으로 원한다mm-dd-yyyy

다음은이 변환을 위해 시도한 샘플 유틸리티입니다.

// Setting the pattern
    SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy");
    // myDate is the java.util.Date in yyyy-mm-dd format
    // Converting it into String using formatter
    String strDate = sm.format(myDate);
    //Converting the String back to java.util.Date
    Date dt = sm.parse(strDate);

여전히 내가 얻는 출력은 형식이 아닙니다 mm-dd-yyyy.

java.util.Datefrom yyyy-mm-ddto 형식을 지정하는 방법을 알려주세요.mm-dd-yyyy


Date Unix 시대 (1970 년 1 월 1 일 00:00:00 UTC) 이후의 밀리 초 수를 나타내는 컨테이너입니다.

형식에 대한 개념이 없습니다.

자바 8 이상

LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);

출력 ...

05-11-2018
2018-05-11
2018-05-11T17:24:42.980

자바 7-

당신은 사용하게해야한다 ThreeTen 백 포트를

원래 답변

예를 들면 ...

Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);

출력 ...

Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013

어떤 형식도 기본 Date을 변경하지 않았습니다 . 이것은 DateFormatters 의 목적입니다

추가 예제로 업데이트 됨

첫 번째 예가 이해가되지 않는 경우를 대비하여 ...

이 예에서는 두 개의 포맷터를 사용하여 동일한 날짜를 포맷합니다. 그런 다음 동일한 포맷터를 사용하여 String값을 Dates로 다시 구문 분석합니다 . 결과 구문 분석은 Date값을보고 하는 방식을 변경하지 않습니다 .

Date#toString내용의 덤프 일뿐입니다. 이것을 변경할 수는 없지만 Date원하는 방식으로 개체의 서식을 지정할 수 있습니다.

try {
    Date myDate = new Date();
    System.out.println(myDate);

    SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
    SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");

    // Format the date to Strings
    String mdy = mdyFormat.format(myDate);
    String dmy = dmyFormat.format(myDate);

    // Results...
    System.out.println(mdy);
    System.out.println(dmy);
    // Parse the Strings back to dates
    // Note, the formats don't "stick" with the Date value
    System.out.println(mdyFormat.parse(mdy));
    System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
    exp.printStackTrace();
}

어떤 출력이 ...

Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013

또한 형식 패턴에주의하십시오. SimpleDateFormat잘못된 패턴을 사용하고 있지 않은지 자세히 살펴보십시오 .)


SimpleDateFormat("MM-dd-yyyy");

대신에

SimpleDateFormat("mm-dd-yyyy");

왜냐하면 MM points Month,mm points minutes

SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);

'M'(대문자)은 월을 나타내고 'm'(단순)은 분을 나타냅니다.

몇 달 동안의 몇 가지 예

'M' -> 7  (without prefix 0 if it is single digit)
'M' -> 12

'MM' -> 07 (with prefix 0 if it is single digit)
'MM' -> 12

'MMM' -> Jul (display with 3 character)

'MMMM' -> December (display with full name)

몇 분의 예

'm' -> 3  (without prefix 0 if it is single digit)
'm' -> 19
'mm' -> 03 (with prefix 0 if it is single digit)
'mm' -> 19

tl; dr

LocalDate.parse( 
    "01-23-2017" , 
    DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)

세부

yyyy-mm-dd 형식의 java.util.Date가 있습니다.

As other mentioned, the Date class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.

java.time

The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.

If you have a java.util.Date, convert to a Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

Time zone

The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.

Define the time zone by which you want context for your Instant.

ZoneId z = ZoneId.of( "America/Montreal" );

Apply the ZoneId to get a ZonedDateTime.

ZonedDateTime zdt = instant.atZone( z );

LocalDate

If you only care about the date without a time-of-day, extract a LocalDate.

LocalDate localDate = zdt.toLocalDate();

To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString. The java.time classes use the standard formats by default when generating/parsing strings.

String output = localDate.toString();

2017-01-23

If you want a MM-DD-YYYY format, define a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );

Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm (minute of hour) rather than MM (month of year).

Use the same DateTimeFormatter object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.

LocalDate localDate = LocalDate.parse( "01-23-2017" , f );

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

Where to obtain the java.time classes?

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.


It is simple use below codes.

final Date todayDate = new Date();

System.out.println(todayDate);

System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(todayDate));

System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(todayDate));

System.out.println(todayDate);

Please change small "mm" month to capital "MM" it will work.for reference below is the sample code.

  **Date myDate = new Date();
    SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");

    String strDate = sm.format(myDate);

    Date dt = sm.parse(strDate);
    System.out.println(strDate);**

참고URL : https://stackoverflow.com/questions/18480633/java-util-date-format-conversion-yyyy-mm-dd-to-mm-dd-yyyy

반응형