这可能是一件非常简单的事情,但我希望以毫秒为单位获取当前日期;即当天午夜的Unix时间戳。我知道我可以通过来做到
long time = System.currentTimeMillis() - new DateTime().millisOfDay().getMillis;
但是,有没有更简单的方法呢?比如,有没有一种方法可以做到这一点,就是一行不减法?
您可以在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
您可以使用日历执行以下操作:
Calendar date = Calendar.getInstance();
long millisecondsDate = date.getTimeInMillis();
谨致问候。
同样简单:
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();