JavaWeb_国际化之DateFormat
国际化之DateFormat
- 1.DateFormat类
1)DateFormat 类可以将一个日期/时间对象格式化为表示某个国家地区的日期/时间字符串,也可以将表示某个本地的日期/时间的字符串解析为相应的日期/时间对象。
2)DateFormat 类定义了一些用于描述日期/时间的显示模式的 int 型的常量,包括FULL, LONG, MEDIUM, DEFAULT, SHORT,这些常量用于描述表示日期/时间字符串的长度。这些常量说明表示的日期/时间的确切格式取决于具体的国家和地区。 - 2.单元测试类
I18nTest
/**
* All rights Reserved,Designed By XS
* @Title: I18nTest.java
* @Package com.xs.i18n
* @Description: TODO
* @author: XS
* @date: 2019年3月23日 下午8:02:52
* @version V1.0
*/
package com.xs.i18n;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.junit.jupiter.api.Test;
/**
* @ClassName: I18nTest
* @Description: TODO
* @author: XS
* @date: 2019年3月23日 下午8:02:52
* @version V1.0
*/
class I18nTest {
@Test
void testDateFormat2() throws ParseException {
String str = "1990-12-12 12:12:12";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = dateFormat.parse(str);
System.out.println(date);
}
/**
* DateFormat: 格式化日期的工具类.
* DateFormate 本身是一个抽象类.
*
* 1. 若只希望通过 DateFormat 把一个 Date 对象转为一个字符串, 则可以通过 DateFormat 的工厂方法来获取 DateFormat 对象
* 2. 可以获取只格式化 Date 的 DateFormat 对象: getDateInstance(int style, Locale aLocale)
* 3. 可以获取只格式化 Time 的 DateFormat 对象: getTimeInstance(int style, Locale aLocale)
* 4. 可以获取既格式化 Date, 也格式化 Time 的 DateFormat 对象: getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)
* 5. 其中 style 可以取值为: DateFormat 的常量: SHORT, MEDIUM, LONG, FULL. Locale 则为代表国家地区的 Locale 对象
* 6. 通过 DateFormat 的 format 方法来格式化个 Date 对象到字符串.
* 7. 若有一个字符串, 如何解析为一个 Date 对象呢 ?
* I. 先创建 DateFormat 对象: 创建 DateFormat 的子类 SimpleDateFormat 对象 SimpleDateFormat(String pattern). 其中 pattern 为日期, 时间的格式, 例如: yyyy-MM-dd hh:mm:ss
* II. 调用 DateFormat 的 parse 方法来解析字符串到 Date 对象.
*
*/
@Test
void testDateFormat() {
Locale locale = Locale.CHINA;
Date date = new Date();
System.out.println(date);
//获取DateFormat对象
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM, locale);
String str = dateFormat.format(date);
System.out.println(str);
}
/**
* Locale: Java 中表示国家或地区的类. JDK 中提供了很多常量.
* 也可以通过 Locale(languageCode, countryCode) 的方式来创建
* 在 WEB 应用中可以通过 request.getLocale() 方法来获取.
*/
@Test
void testLocale() {
Locale locale = Locale.CHINA;
System.out.println(locale.getDisplayCountry());
System.out.println(locale.getLanguage());
locale = new Locale("en", "US");
System.out.println(locale.getDisplayCountry());
System.out.println(locale.getLanguage());
}
}