如何从时间戳中删除毫秒?

时间:2012-03-09 17:23:56

标签: java timestamp

我被问到这个问题:

将时间戳作为long值,在Java中编写实用程序函数以减少毫秒数。 例如,给定输入1274883865399(实际时间:20100526T14:24:25.399Z), 功能将返回1274883865000(实际时间:2010-05-26T14:24:25.000Z)

我这样做了:

import java.text.*;
import java.util.*;

public class ClearMilliSeconds {
    public static void main(String[] args) {   

        long yourmilliseconds = 1274883865399L;
        SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
         Calendar c = Calendar.getInstance();


        Date resultdate = new Date(yourmilliseconds);
        c.set(Calendar.MILLISECOND, 0);
        resultdate.setTime(c.getTimeInMillis());
        System.out.println(sdf.format(resultdate)); 
}
}

但它没有给我正确的结果

3 个答案:

答案 0 :(得分:29)

如果我理解正确,则无需使用日期/日历...

long yourmilliseconds = 1274883865399L;
long droppedMillis = 1000 * (yourmilliseconds/ 1000);    
System.out.println(droppedMillis);

1274883865000

或者...如果您希望进行日期格式化...

Calendar c = Calendar.getInstance();
c.setTime(new Date(yourmilliseconds));
c.set(Calendar.MILLISECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm.ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(c.getTime()));

2010-05-26T14:24.25.000Z

答案 1 :(得分:1)

如果同样的问题将我的初始时间戳存储在sq中 做了sq.setTime(1000*(long)Math.floor(sq.getTime()/ 1000));做了这个工作。在我的情况下,sq是sql.Timestamp

答案 2 :(得分:0)

您的代码有错误:您没有将毫秒数应用于c(Calendar)。解决方法,使其保持在代码的范围内:

import java.text.*;
import java.util.*;

public class ClearMilliSeconds {
    public static void main(String[] args) {   

     long yourmilliseconds = 1274883865399L;
     Calendar c = Calendar.getInstance();        
     c.setTimeInMillis(yourmilliseconds);
     c.set(Calendar.MILLISECOND, 0);

     Date resultdate = new Date(c.getTimeInMillis());
     SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
     System.out.println(sdf.format(resultdate)); 

} }