这可能是一个非常简单的问题,但我希望以毫秒为单位得到当天;也就是说,当天午夜的Unix时间戳。我知道我可以通过
来做到这一点long time = System.currentTimeMillis() - new DateTime().millisOfDay().getMillis;
但是,有没有办法做到这一点更简单?比如,有没有办法做到这一点是一行不减去?
答案 0 :(得分:5)
你可以在Java 8中这样做:
ZonedDateTime startOfToday = LocalDate.now().atStartOfDay(ZoneId.systemDefault());
long todayMillis1 = startOfToday.toEpochSecond() * 1000;
或者在任何类似的Java版本中:
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
cal.clear();
cal.set(year, month, date);
long todayMillis2 = cal.getTimeInMillis();
使用以下方式打印结果:
System.out.println("Today is " + startOfToday);
System.out.println(todayMillis1);
System.out.println(todayMillis2);
会给你这个输出:
Today is 2016-08-03T00:00-04:00[America/New_York]
1470196800000
1470196800000
答案 1 :(得分:1)
您可以使用日历:
执行以下操作Calendar date = Calendar.getInstance();
long millisecondsDate = date.getTimeInMillis();
问候。
答案 2 :(得分:0)
同样简单:
GregorianCalendar now = new GregorianCalendar();
GregorianCalendar start = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
long ms = now.getTimeInMillis() - start.getTimeInMillis();
或:
GregorianCalendar now = new GregorianCalendar();
long ms = now.getTimeInMillis() - new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)).getTimeInMillis();