是否可以使用 Java 8 将日期截断为月份?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30775521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to truncate date to Month with Java 8?
提问by EnverOsmanov
I want to get the milliseconds truncated to days, I can use
我想将毫秒截断为天,我可以使用
Instant.now().truncatedTo(ChronoUnit.DAYS).toEpochMilli()
But I can't truncate to ChronoUnit.MONTH
(it throws an exception). Do I need use a Calendar?
但我不能截断到ChronoUnit.MONTH
(它抛出异常)。我需要使用日历吗?
采纳答案by assylias
One way would be to manually set the day to the first of the month:
一种方法是手动将日期设置为每月的第一天:
import static java.time.ZoneOffset.UTC;
import static java.time.temporal.ChronoUnit.DAYS;
ZonedDateTime truncatedToMonth = ZonedDateTime.now(UTC).truncatedTo(DAYS).withDayOfMonth(1);
System.out.println(truncatedToMonth); //prints 2015-06-01T00:00Z
long millis = truncatedToMonth.toInstant().toEpochMilli();
System.out.println(millis); // prints 1433116800000
Or an alternative with a LocalDate
, which is maybe cleaner:
或者使用 a 的替代方案LocalDate
,这可能更清洁:
LocalDate firstOfMonth = LocalDate.now(UTC).withDayOfMonth(1);
long millis = firstOfMonth.atStartOfDay(UTC).toEpochSecond() * 1000;
//or
long millis = firstOfMonth.atStartOfDay(UTC).toInstant().toEpochMilli();
回答by Simon
This is what java.time.temporal.TemporalAdjusters
are for.
这是java.time.temporal.TemporalAdjusters
为了什么。
date.with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.DAYS);
回答by MozenRath
For a simple way to do it:
一个简单的方法来做到这一点:
Calendar cal = new GregorianCalendar();
System.out.println(cal.getTime());
cal.set(Calendar.DAY_OF_MONTH,1);
System.out.println(cal.getTime());
cal.set(Calendar.HOUR_OF_DAY,0);
System.out.println(cal.getTime());
cal.set(Calendar.MINUTE,0);
System.out.println(cal.getTime());
cal.set(Calendar.SECOND,0);
System.out.println(cal.getTime());
cal.set(Calendar.MILLISECOND,0);
System.out.println(cal.getTime());
The output is:
输出是:
Thu Jun 11 05:36:17 EDT 2015
Mon Jun 01 05:36:17 EDT 2015
Mon Jun 01 00:36:17 EDT 2015
Mon Jun 01 00:00:17 EDT 2015
Mon Jun 01 00:00:00 EDT 2015
Mon Jun 01 00:00:00 EDT 2015
回答by epcpu
I had same problem of course in working with instants, then following code solved my problem:
我当然在处理瞬间时遇到了同样的问题,然后下面的代码解决了我的问题:
Instant instant = Instant.ofEpochSecond(longTimestamp);
instant = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()).with(TemporalAdjusters.firstDayOfMonth())
.truncatedTo(ChronoUnit.DAYS).toInstant();