How to convert a FileTime to a Date using Java

A Date object can be created using the number of milliseconds since epoch from a FileTime.


Date newDate = new Date( filetime.toMillis() );


This example creates a Date called firstDate, no parameter is passed to the constructor, this way the value used is the current date and time. That date is converted to a FileTime using the fromMillis method of the FileTime object. The second Date object is then created passing the number of milliseconds of the FileTime since epoch in the constructor. The three values are then written in the output showing that they are identical. A final test checks that the values are the same, then we format the Date using SimpleDateFormat. The human readable value is then written in the output.

import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileTimeDate {

    public static void main(String[] argv) {

	Date firstDate = new Date();
	FileTime time = FileTime.fromMillis( firstDate.getTime() );

	Date newDate = new Date( time.toMillis() );
	System.out.println("firstDate milliseconds:\t" +  firstDate.getTime() );
	System.out.println("FileTime milliseconds:\t" + time.toMillis() );
	System.out.println("newDate milliseconds:\t" + newDate.getTime() );

	if( time.toMillis() ==  firstDate.getTime() && newDate.getTime() ==  time.toMillis()){
	    String pattern = "yyyy-MM-dd HH:mm:ss";
	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
	    System.out.println("All the Dates are equal: " + simpleDateFormat.format( firstDate ) );


The output will be:

firstDate milliseconds:	1525827617236
FileTime milliseconds:	1525827617236
newDate milliseconds:	1525827617236
All the Dates are equal: 2018-05-08 18:00:17

The FileTime object is immutable, it does not change once it has been created. This ensure that the value will not change when using this object. The Date Object is not thread safe.



Share this article:

Recent Comments