java 日期格式化SimpleDateFormat Local西班牙等国家的日期格式化

来源:互联网 发布:团购的软件 编辑:程序博客网 时间:2024/05/18 03:41

今天在开发的过程中遇到了多语言日期格式化的问题,所有在此记录下,以便下次备忘。

java.text.SimpleDateFormat.SimpleDateFormat(String pattern, Locale locale) 中的Locale只给我们提供了部分国家作为常量来供我们调用,当我们遇到像西班牙这样它并没有提供给我们常量的国家时,我们应该怎么样来对其日期进行格式化呢?

之前百度了都没找到方案,所有就去stackoverflow里参考了下国外网友的想法,接下来上代码:


<span style="font-size:18px;">/* * 根据国家对相应的时间进行日期格式化 */public static Date dateFormate(String dateStr, int countryid) throws ParseException {Countries countries = countriesMapper.selectByPrimaryKey(countryid);SimpleDateFormat format = null;if ("DE".equals(countries.getAlpha2())) {format = new SimpleDateFormat("dd. MMMM yyyy", Locale.GERMAN);} else if ("GB".equals(countries.getAlpha2())) {format = new SimpleDateFormat("dd MMMM yyyy", Locale.ENGLISH);} else if ("IT".equals(countries.getAlpha2())) {format = new SimpleDateFormat("dd MMMM yyyy", Locale.ITALY);dateStr = dateStr.toUpperCase();} else if ("FR".equals(countries.getAlpha2())) {format = new SimpleDateFormat("dd MMMM yyyy", Locale.FRANCE);dateStr = dateStr.toUpperCase();} else if ("ES".equals(countries.getAlpha2())) {format = new SimpleDateFormat("d 'de' MMMM 'de' yyyy", new Locale("es", "ES"));} else if ("JP".equals(countries.getAlpha2())) {format = new SimpleDateFormat("yyyy'年'MM'月'dd'日'", Locale.JAPAN);}else if ("US".equals(countries.getAlpha2())) {format = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);}else if ("CA".equals(countries.getAlpha2())) {format = new SimpleDateFormat("MMMM dd, yyyy", Locale.CANADA);}return format.parse(dateStr);}</span>

对于Locale没有提供常量的国家我们可以通过创建Locale对象的方式实现:
<span style="font-size:18px;">format = new SimpleDateFormat("d 'de' MMMM 'de' yyyy", new Locale("es", "ES"));</span>


以上是我的总结,欢迎大家补充,谢谢。

0 0
原创粉丝点击