Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove milliseconds from a timestamp?

Tags:

java

timestamp

I was asked this question :

Given a timestamp as a long value, write a utility function in Java to drop the milliseconds. For example, given an input of 1274883865399 (actual time: 20100526T14:24:25.399Z), the function would return 1274883865000 (actual time: 2010-05-26T14:24:25.000Z)

I did this :

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)); 
}
}

But it did not give me the right result

like image 401
Majid Kamal Avatar asked Mar 09 '12 17:03

Majid Kamal


People also ask

How do you convert timestamps to milliseconds to seconds?

Take Input in milliseconds. Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).

How do you convert datetime to milliseconds?

To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.


2 Answers

If I understand you correctly there is no need to use Date / Calendar...

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

1274883865000

Or... if you wish to have date formatting...

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

like image 146
Adam Avatar answered Sep 26 '22 21:09

Adam


Had same issue had my initial timestamp stored in sq and did sq.setTime(1000*(long)Math.floor(sq.getTime()/ 1000)); that does the job. In my case sq is a sql.Timestamp

like image 23
TomFree Avatar answered Sep 22 '22 21:09

TomFree