如何在java中以毫秒为单位获取当前小时?
你可以尝试这样的。
Calendar c = Calendar.getInstance(); //Get current time
//set miliseconds,seconds,minutes to 0 so we get exactly the hour
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MINUTE, 0);
// This gets the time in milliseconds
long result=c.getTime().getTime();
明白了......你能解释一下你在做什么吗? –
我试图在编辑中解释。从当前时间中删除分钟/秒/毫秒,然后以毫秒为单位获取它 –
@AmitDas他将日历值设置为当前系统时间。这还包括时间戳,这就是他将分,秒和毫秒设置为零的原因。剩下的只是日期+小时,然后他转换为长期价值。 – MihaiC
与Java 8 ...
LocalDateTime ldt = LocalDateTime.of(2015, Month.MAY, 4, 4, 30);
ldt = ldt.withMinute(0).withSecond(0).withNano(0);
long millisSinceEpoch = ldt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
的基本思路是采取“时间”零出元素,你不想和结果转换为毫秒...
也...
如果你不喜欢打字,你可以使用...
ldt = ldt.truncatedTo(ChronoUnit.HOURS);
代替ldt = ldt.withMinute(0).withSecond(0).withNano(0)
有一些像乔达的'hourOfDay()。roundFloorCopy()',不是吗? – shmosel
@shmosel不知道,看看文档:P – MadProgrammer
@shmosel你可能在['LocalDateTime#truncatedTo']之后(https://docs.oracle.com/javase/8/docs/api/java/ time/LocalDateTime.html#truncatedTo-java.time.temporal.TemporalUnit-) – MadProgrammer
Long time = System.currentTimeMillis();
time = time/3600000;
time = time * 3600000;
或更短的版本:
Long time = (System.currentTimeMillis()/3600000)*3600000;
注意:3600000 =60分钟* 60秒*的1000个milisecs。原理:当你做第一个整数除以3600000时,你将“丢失”有关分,秒和毫秒的信息。但结果是几小时,而不是几毫秒。让时间回到毫秒简单乘以3600000.
乍一看,它可能看起来除以3600000和乘以3600000将相当于“什么都不做”,但由于整数算术结果是你想要的(摆脱分钟,秒和毫秒信息)。
在Joda-Time 2.7,在DateTime
对象上调用getMillisOfSecond
方法返回int
。
int millisOfSecond = DateTime.now(DateTimeZone.forID("Africa/Casablanca")).getMillisOfSecond() ;
毫秒以来什么时候? – MadProgrammer
自开创以来 –