在Java中使用本地化时,如何完整显示年份?
上述方法对在Java中使用本地化时,如何完整显示年份?,java,date,date-format,Java,Date,Date Format,上述方法对Locale.UK返回“14/06/12”,对Locale.US返回“06/14/12” 我如何才能让它完整地返回年份,即美国地区的“2012年6月14日”和英国地区的“2012年6月14日”您必须希望您的日期格式是SimpleDataFormat的一个实例,因此,您可以获得其模式,并将其从两年更改为四年。您必须获得locale模式,并将额外的yy附加到格式中 这可以帮助你- private String setDate(int day) { Calendar cal = Ca
Locale.UK
返回“14/06/12”,对Locale.US
返回“06/14/12”
我如何才能让它完整地返回年份,即美国地区的“2012年6月14日”和英国地区的“2012年6月14日”您必须希望您的
日期格式是SimpleDataFormat
的一个实例,因此,您可以获得其模式,并将其从两年更改为四年。您必须获得locale
模式,并将额外的yy
附加到格式中
这可以帮助你-
private String setDate(int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, + day);
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
String formattedDate = df.format(cal.getTime());
return formattedDate;
}
这将适用于最终返回2位数年份的所有模式
我有sdf.toPattern.concat(“yy”)
,它只适用于那些最终拥有yy
的Locale
。然而,Dragon66使用替换(“yy”,“yyyy”)
的想法将适用于所有地区JHS的答案几乎是完整的。唯一需要做的就是让它适用于所有地区
private String setDate(int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, + day);
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
// code modified from here
SimpleDateFormat sdf = (SimpleDateFormat) df;
sdf.applyPattern(sdf.toPattern().replace("yy","yyyy")); // replacing to yyyy
String formattedDate = sdf.format(cal.getTime());
return formattedDate;
}
以下是Greg的评论(感谢Greg),这里是javadoc的相关注释:
“如果您希望对格式或解析有更多的控制,(或者希望给用户更多的控制权),您可以尝试将出厂方法中获得的DateFormat
转换为SimpleDateFormat
。这对大多数国家/地区都适用;只要记住将其放入try
块中,以防遇到异常。“谢谢。但是如果我使用一个模式和格式,那么它会给我2012年的“yyyy”模式,或者如果我使用“MM/dd/yyyy”模式对英国不可取,而“dd/MM/yyyy”模式对我们不可取。@AmirGhahrai看起来Juniad比我解释得更好。原始模式,假设它是一个简单的日期格式,不一定以yy
结尾。解决方案是将DateFormat int
和大部分区域设置
结合起来,对于Date
则以yy
结尾。另外,我在末尾添加了一行-仅适用于结尾有2位数年份的模式。对我们和英国来说都很好。谢谢大家。非常有用。虽然它非常适合英国、美国,但对于日期从年开始的地区,它似乎失败了,例如,日本是2012-06-14,使用上述解决方案,我得到12-06-1412字符串模式=sdf.toPattern().replaceAll(“y+”,“yyyy”);应用模式(模式)@龙66:你有到目前为止最好的答案-请把它作为一个答案贴出来。您可能希望包含来自javadoc的注释:“如果您想要对格式或解析进行更多的控制,(或者想要给您的用户更多的控制权),您可以尝试将从工厂方法获得的DateFormat
转换为SimpleDateFormat
。这对大多数国家都适用;只要记住将其放入try
块中,以防遇到不寻常的情况。“很好。”<代码>替换
而不是concat
。由于匆忙,我没有想到这件事。回答得好。被接受的答案似乎适用于所有国家。
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Locale;
class ChangeDateFormat
{
private String setDate(int day, Locale locale) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, +day);
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
if (df instanceof SimpleDateFormat)
{
SimpleDateFormat sdf = (SimpleDateFormat) df;
// To show Locale specific short date expression with full year
String pattern = sdf.toPattern().replaceAll("y+","yyyy");
sdf.applyPattern(pattern);
return sdf.format(cal.getTime());
}
String formattedDate = df.format(cal.getTime());
return formattedDate;
}
public static void main(String[] args)
{
ChangeDateFormat cdf = new ChangeDateFormat();
System.out.println(cdf.setDate(1, Locale.JAPAN));
}
}