Monday, 27 November 2023

Get the current date, with the milliseconds removed

Following snippet return a new Date object by removing the milliseconds.

public static Date removeMilliSeconds(Date date) {
	// Get the number of milliseconds since January 1, 1970, 00:00:00 GMT
	// represented by this Date object.
	long timeInMilliSeconds = date.getTime();
	long timeInSeconds = timeInMilliSeconds / 1000;

	return new Date(timeInSeconds * 1000L);
}

Explanation:

a.   The getTime() method of the Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GMT (the epoch).

b.   The variable timeInMilliSeconds stores the time represented by the input Date object in milliseconds.

c.    The code then converts this time from milliseconds to seconds by dividing timeInMilliSeconds by 1000, resulting in timeInSeconds.

d.   Finally, a new Date object is created using the time in seconds. The multiplication by 1000L is done to convert the time back to milliseconds, and this effectively sets the milliseconds part to zero, as it is now a multiple of 1000.

 

In summary, the purpose of this method is to remove the milliseconds from a given Date object by creating a new Date object with the same date and time but with the milliseconds set to zero.

 

Find the below working application.

 

RemoveMilliSecondsFromDate.java

package com.sample.app;

import java.text.SimpleDateFormat;
import java.util.Date;

public class RemoveMilliSecondsFromDate {

	public static Date removeMilliSeconds(Date date) {

		// Get the number of milliseconds since January 1, 1970, 00:00:00 GMT
		// represented by this Date object.
		long timeInMilliSeconds = date.getTime();
		long timeInSeconds = timeInMilliSeconds / 1000;

		return new Date(timeInSeconds * 1000L);
	}

	public static String formattedDateStr(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		return sdf.format(date);
	}

	public static void main(String[] args) {
		Date date = new Date();

		System.out.println("date : " + formattedDateStr(date));
		System.out.println("date after removing milliseconds: " + formattedDateStr(removeMilliSeconds(date)));
	}

}

Output

date : 2023-11-28 10:28:08.233
date after removing milliseconds: 2023-11-28 10:28:08.000

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment