Programing

SimpleDateFormat 및 로케일 기반 형식 문자열

lottogame 2020. 10. 23. 07:30
반응형

SimpleDateFormat 및 로케일 기반 형식 문자열


주어진 로케일에 따라 다른 방식으로 Java에서 날짜 형식을 지정하려고합니다. 예를 들어 영어 사용자는 "2009 년 11 월 1 일"( "MMM d, yyyy"형식)을, 노르웨이 사용자는 "1. nov. 2009"( "d. MMM. yyyy")를 확인하고 싶습니다.

SimpleDateFormat 생성자에 로케일을 추가하면 월 부분은 정상적으로 작동하지만 나머지는 어떻습니까?

로케일과 쌍을 이루는 형식 문자열을 SimpleDateFormat에 추가 할 수 있기를 바랐지만이 작업을 수행 할 방법을 찾을 수 없습니다. 가능합니까 아니면 내 코드가 로케일을 확인하고 해당 형식 문자열을 추가하도록해야합니까?


를 사용 하여 고유 한 패턴을 만드는 대신 DateFormat.getDateInstance (int style, Locale locale)를 사용합니다 SimpleDateFormat.


SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
String formatted = dateFormat.format(the_date_you_want_here);

사용 스타일 + 로케일 : DateFormat.getDateInstance (INT 스타일, 로케일 로케일)

http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html 확인

다음 예제를 실행하여 차이점을 확인하십시오.

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

public class DateFormatDemoSO {
  public static void main(String args[]) {
    int style = DateFormat.MEDIUM;
    //Also try with style = DateFormat.FULL and DateFormat.SHORT
    Date date = new Date();
    DateFormat df;
    df = DateFormat.getDateInstance(style, Locale.UK);
    System.out.println("United Kingdom: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.US);
    System.out.println("USA: " + df.format(date));   
    df = DateFormat.getDateInstance(style, Locale.FRANCE);
    System.out.println("France: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.ITALY);
    System.out.println("Italy: " + df.format(date));
    df = DateFormat.getDateInstance(style, Locale.JAPAN);
    System.out.println("Japan: " + df.format(date));
  }
}

산출:

United Kingdom: 25-Sep-2017
USA: Sep 25, 2017
France: 25 sept. 2017
Italy: 25-set-2017
Japan: 2017/09/25

tl; dr

LocalDate.now().format(
    DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM )
                     .withLocale( new Locale( "no" , "NO" ) )
)

의 번잡 한 클래스 java.util.Date와는 SimpleDateFormat이제 java.time 클래스에 의해 대체 유산이다.

LocalDate

LocalDate클래스는 시간이 하루의 시간 영역없이없이 날짜 만 값을 나타냅니다.

시간대는 날짜를 결정하는 데 중요합니다. 주어진 순간에 날짜는 지역별로 전 세계적으로 다릅니다. 예를 들어, 파리 에서 자정 이후 몇 분이 지나면 프랑스몬트리올 퀘벡 에서는 여전히 '어제'인 새로운 날 입니다.

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

DateTimeFormatter

DateTimeFormatter날짜 부분 또는 시간 부분 만 나타내는 문자열을 생성하는 데 사용 합니다.

DateTimeFormatter클래스는 자동으로 할 수 지역화 .

현지화하려면 다음을 지정하십시오.

  • FormatStyle 문자열의 길이 또는 약자를 결정합니다.
  • Locale (a) 요일, 월 이름 등의 번역을위한 인간 언어, (b) 약어, 대문자, 구두점 등의 문제를 결정하는 문화적 규범을 결정합니다.

예:

Locale l = Locale.CANADA_FRENCH ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( l );
String output = ld.format( f );

다른 방향으로 가면 현지화 된 문자열을 구문 분석 할 수 있습니다.

LocalDate ld = LocalDate.parse( input , f );

로케일과 시간대는 완전히 직교하는 문제입니다. 몬트리올 순간을 일본어로 발표하거나 오클랜드 뉴질랜드 순간을 힌디어로 발표 할 수 있습니다.

다른 예 : 6 junio 2012(스페인어)를 2012-06-06(표준 ISO 8601 형식)으로 변경합니다. java.time 클래스는 문자열 구문 분석 / 생성에 기본적으로 ISO 8601 형식을 사용합니다.

String input = "6 junio 2012";
Locale l = new Locale ( "es" , "ES" );
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "d MMMM uuuu" , l );
LocalDate ld = LocalDate.parse ( input , f );
String output = ld.toString();  // 2012-06-06. 

형식 정독

다음은 자동으로 현지화 된 여러 로케일에서 여러 형식의 결과를 정독하는 몇 가지 예제 코드입니다.

An EnumSet객체를 Set수집 할 때 낮은 메모리 사용량과 빠른 실행 속도 모두에 최적화 된 의 구현입니다 Enum. 따라서 루프 할 EnumSet.allOf( FormatStyle.class )네 가지 FormatStyle열거 형 개체 의 컬렉션을 모두 제공 합니다. 자세한 내용 은 enum 유형에 대한 Oracle Tutorial을 참조하십시오 .

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 );

List < Locale > locales = new ArrayList <>( 3 );
locales.add( Locale.CANADA_FRENCH );
locales.add( new Locale( "no" , "NO" ) );
locales.add( Locale.US );

// Or use all locales (almost 800 of them, for about 120K text results).
// Locale[] locales = Locale.getAvailableLocales(); // All known locales. Almost 800 of them.

for ( Locale locale : locales )
{
    System.out.println( "------|  LOCALE: " + locale + " — " + locale.getDisplayName() + "  |----------------------------------" + System.lineSeparator() );

    for ( FormatStyle style : EnumSet.allOf( FormatStyle.class ) )
    {
        DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale );
        String output = ld.format( f );
        System.out.println( output );
    }
    System.out.println( "" );
}
System.out.println( "« fin »" + System.lineSeparator() );

산출.

------|  LOCALE: fr_CA — French (Canada)  |----------------------------------

mardi 23 janvier 2018
23 janvier 2018
23 janv. 2018
18-01-23

------|  LOCALE: no_NO — Norwegian (Norway)  |----------------------------------

tirsdag 23. januar 2018
23. januar 2018
23. jan. 2018
23.01.2018

------|  LOCALE: en_US — English (United States)  |----------------------------------

Tuesday, January 23, 2018
January 23, 2018
Jan 23, 2018
1/23/18

« fin »

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?

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.


Localization of date string:

Based on redsonic's post:

private String localizeDate(String inputdate, Locale locale) { 

    Date date = new Date();
    SimpleDateFormat dateFormatCN = new SimpleDateFormat("dd-MMM-yyyy", locale);       
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");


    try {
        date = dateFormat.parse(inputdate);
    } catch (ParseException e) {
        log.warn("Input date was not correct. Can not localize it.");
        return inputdate;
    }
    return dateFormatCN.format(date);
}

String localizedDate = localizeDate("05-Sep-2013", new Locale("zh","CN"));

will be like 05-九月-2013


This will display the date according to user's current locale:

To return date and time:

import java.text.DateFormat;    
import java.util.Date;

Date date = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
String myDate = df.format(date);

Dec 31, 1969 7:00:02 PM

To return date only, use:

DateFormat.getDateInstance() 

Dec 31, 1969


String text = new SimpleDateFormat("E, MMM d, yyyy").format(date);

Java 8 Style for a given date

LocalDate today = LocalDate.of(1982, Month.AUGUST, 31);
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.ENGLISH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.FRENCH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.JAPANESE)));

Java8

 import java.time.format.DateTimeFormatter;         
 myDate.format(DateTimeFormatter.ofPattern("dd-MMM-YYYY",new Locale("ar")))

참고URL : https://stackoverflow.com/questions/1661325/simpledateformat-and-locale-based-format-string

반응형