确定模式给出的时间范围
可以使用例如 SimpleDateFormat(formatPattern, locale) 来格式化日期。 是否可以以某种方式确定给定日期的 formatPattern 表示的时间段(以秒为单位)?例如,如果我们有
Date date = new Date(1286488800);
String formatPattern = "yyyy";
可能确定 formatPattern 表示的年份长度(以秒为单位)以及日期所在的位置?
A date can be formatted using a e.g. SimpleDateFormat(formatPattern, locale).
Is it somehow possible to determine the time period (in seconds) that is represented by formatPattern given a date? E.g. if we have
Date date = new Date(1286488800);
String formatPattern = "yyyy";
is it possible to determine the length of the year (in seconds) represented by formatPattern and in which date lies?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为使用 formatPattern 来检测日期范围是一件坏事。您需要为日期模式编写一个解析器。更好的想法是使用包含可能范围(年、月、周等)的下拉列表。那么以秒为单位计算当前范围的长度就不成问题了。
I think a to use a formatPattern to detect a date range is a bad thing. You need to write a parser for the date pattern. A better idea is to use a drop down list with possible ranges (year, month, week, etc.). Then it not a problem to calculate the length of the current range in seconds.
我相信已经找到了适当的解决方案。它对我有用,尽管我不确定也没有测试这是否在每种情况下都准确有效(例如闰秒)。如果您有改进建议,请随时发布。代码如下:
它的工作原理基本上是,将日历集的日历字段与使用所有字段 (oddestDate) 的日期进行比较,并将日历设置为相同日期,但由 formatPattern 再次格式化、打印和解析。为了至少补偿闰年,还需要 inputDate。
I believe to have found a proper solution for this. It works for me, although I am not sure and haven't tested whether this works precisely in every situtions (e.g. with leap seconds). If you have suggestions for improvement, feel free to post them. Here is the code:
It basically works by comparing the calender fields of a calendar set to a date that uses all fields (oddestDate) with a calendar set to the same date but formatted, printed, and parsed again by the formatPattern. To compensate at least for leap years, an inputDate is also required.