我有 LocalDate其中包含日期 2012-12-28 并且我想用本地化月份名称(即波兰语中的 12 月)属格 打印它,这在波兰语中与主格不同(grudnia 和grudzień)。因为我也想使用自定义格式,所以我创建了自己的 DateTimeFormatter使用 DateTimeFormatterBuilder (在 Joda-Time 中,AFAIK 是正确的方法):
private static final DateTimeFormatter CUSTOM_DATE_FORMATTER
= new DateTimeFormatterBuilder()
.appendLiteral("z dnia ")
.appendDayOfMonth(1)
.appendLiteral(' ')
.appendText(new MonthNameGenitive()) // <--
.appendLiteral(' ')
.appendYear(4, 4)
.appendLiteral(" r.")
.toFormatter()
.withLocale(new Locale("pl", "PL")); // not used in this case apparently
输出应该是“z dnia 28 grudnia 2012 r.”。
我的问题是关于标有箭头的行:我应该如何实现 MonthNameGenitive ?目前它扩展DateTimeFieldType并且有相当多的代码:
final class MonthNameGenitive extends DateTimeFieldType {
private static final long serialVersionUID = 1L;
MonthNameGenitive() {
super("monthNameGenitive");
}
@Override
public DurationFieldType getDurationType() {
return DurationFieldType.months();
}
@Override
public DurationFieldType getRangeDurationType() {
return DurationFieldType.years();
}
@Override
public DateTimeField getField(final Chronology chronology) {
return new MonthNameGenDateTimeField(chronology.monthOfYear());
}
private static final class MonthNameGenDateTimeField
extends DelegatedDateTimeField {
private static final long serialVersionUID = 1L;
private static final ImmutableList<String> MONTH_NAMES =
ImmutableList.of(
"stycznia", "lutego", "marca", "kwietnia", "maja", "czerwca",
"lipca", "sierpnia", "września", "października", "listopada",
"grudnia");
private MonthNameGenDateTimeField(final DateTimeField field) {
super(field);
}
@Override
public String getAsText(final ReadablePartial partial,
final Locale locale) {
return MONTH_NAMES.get(
partial.get(this.getType()) - 1); // months are 1-based
}
}
}
对我来说似乎很草率而且不是防弹的,因为我必须实现许多魔术方法,而且我正在使用 DelegatedDateTimeField并仅覆盖一种方法( getAsText(ReadablePartial, Locale) ),而其他方法同名:
getAsText(long, Locale) getAsText(long) getAsText(ReadablePartial, int, Locale) getAsText(int, Locale) 是否有更好的方法来获得所需的输出(使用 DateTimeFormatter )或者我的方法正确但非常冗长?
编辑:
我尝试使用新的 JDK8 Time API(类似于 Joda,基于 JSR-310)来实现相同的目标,并且可以轻松完成:
private static final java.time.format.DateTimeFormatter JDK8_DATE_FORMATTER
= new java.time.format.DateTimeFormatterBuilder()
.appendLiteral("z dnia ")
.appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NORMAL)
.appendLiteral(' ')
.appendText(ChronoField.MONTH_OF_YEAR, MONTH_NAMES_GENITIVE) // <--
.appendLiteral(' ')
.appendValue(ChronoField.YEAR, 4)
.appendLiteral(" r.")
.toFormatter()
.withLocale(new Locale("pl", "PL"));
在哪里 MONTH_NAMES_GENITIVE是 Map<Long, String>带有自定义月份名称,因此非常易于使用。见 DateTimeFormatterBuilder#appendText(TemporalField, Map) .
有趣的是,在 JDK8 中,整个波兰月名属格的玩法是不必要的,因为 DateFormatSymbols.getInstance(new Locale("pl", "PL")).getMonths()默认情况下以属格返回月份名称... 虽然此更改对于我的用例是正确的(在波兰语中,我们说“今天是 2012 年 12 月 28 日”,使用属格中的月份名称),但在其他一些情况(我们用主格说“这是 2012 年 12 月”)并且它是向后不兼容的。
最佳答案
你有我的同情 - Joda Time 中的场系统有些复杂。
但是,我建议在这种情况下,最简单的方法实际上是使用 DateTimeFormatterBuilder.append(DateTimePrinter 打印机)。请注意,这种方法仅仅在您只对打印感兴趣时才有效 - 如果您还需要解析,生活就会变得更加复杂。
此时您只需要实现 DateTimePrinter,这相对很简单,特别是如果您乐于忽略 Locale 作为你只对单一文化感兴趣。您可以将所有逻辑(不会太多)放在一个方法中,并使其余方法仅委托(delegate)给该方法。对于需要 long 和 DateTimeZone 的重载,只需构造一个 DateTime 并调用 toLocalDateTime,此时您可以委托(delegate)给其他方法。
编辑:事实上,一个选择是编写一个抽象基类,如果你知道你只关心本地值:
public abstract class SimpleDateTimePrinter implements DateTimePrinter {
protected abstract String getText(ReadablePartial partial, Locale locale);
@Override
public void printTo(StringBuffer buf, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale) {
DateTime dateTime = new DateTime(instant, chrono.withZone(displayZone));
String text = getText(dateTime.toLocalDateTime(), locale);
buf.append(text);
}
@Override
public void printTo(Writer out, long instant, Chronology chrono,
int displayOffset, DateTimeZone displayZone, Locale locale)
throws IOException {
DateTime dateTime = new DateTime(instant, chrono.withZone(displayZone));
String text = getText(dateTime.toLocalDateTime(), locale);
out.write(text);
}
@Override
public void printTo(StringBuffer buf, ReadablePartial partial, Locale locale) {
buf.append(getText(partial, locale));
}
@Override
public void printTo(Writer out, ReadablePartial partial, Locale locale)
throws IOException {
out.write(getText(partial, locale));
}
}
然后您可以轻松编写一个忽略语言环境的具体子类,只返回月份:
public class PolishGenitiveMonthPrinter extends SimpleDateTimePrinter {
private static final ImmutableList<String> MONTH_NAMES =
ImmutableList.of(
"stycznia", "lutego", "marca", "kwietnia", "maja", "czerwca",
"lipca", "sierpnia", "września", "października", "listopada",
"grudnia");
private static final int MAX_MONTH_LENGTH;
static {
int max = 0;
for (String month : MONTH_NAMES) {
if (month.length() > max) {
max = month.length();
}
}
MAX_MONTH_LENGTH = max;
}
@Override
public int estimatePrintedLength() {
return MAX_MONTH_LENGTH;
}
@Override
protected String getText(ReadablePartial partial, Locale locale) {
int month = partial.get(DateTimeFieldType.monthOfYear());
return MONTH_NAMES.get(month - 1);
}
}
当然,您可以在一个类中完成所有这些操作,但我可能会拆分它以使基类在将来更可重用。
关于java - 带有 Joda-Time DateTimeFormatter 的属格(波兰语语言环境)月份名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17188316/
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/
HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候
遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg
当我创建一个Rails应用程序时,控制台:railsnewfoo我的代码可以使用字符串“foo”吗?puts"Yourapp'snameis"+app_name_bar 最佳答案 Rails.application.class将为您提供应用程序的全名(例如YourAppName::Application)。从那里您可以使用Rails.application.class.parent获取模块名称。 关于ruby-on-rails-应用程序的名称是否可以作为变量使用?,我们在StackOve
已经有一个问题回答了如何将“America/Los_Angeles”转换为“PacificTime(US&Canada)”。但是我想将“美国/太平洋”和其他过时的时区转换为RailsTimeZone。我无法在图书馆中找到任何可以帮助我完成此任务的东西。 最佳答案 来自RailsActiveSupport::TimeZonedocs:TheversionofTZInfobundledwithActiveSupportonlyincludesthedefinitionsnecessarytosupportthezonesdefinedb