How to convert a FileTime to a LocalDateTime using Java

A FileTime Object is converted to a LocalDateTime using the Instant Object in Java


LocalDateTime ldt =  LocalDateTime.ofInstant( FILE_TIME.toInstant(), ZoneId.systemDefault());


This example creates a Date Object with the current date. The Object is converted to FileTime using the current time. That FileTime is then converted to LocalDateTime using an Instant. All three dates are converted to epoc to show that they reprensent the same date. The LocalDateTime is formatted using a DateTimeFormatter and the Medium format, the value is localized and displayed in the output.

import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class FileTimeDateTime {

    public static void main(String[] argv) {

	// Create the date
	Date firstDate = new Date();
	// Create the FileTime from a Date
	FileTime time = FileTime.fromMillis( firstDate.getTime() );

	// Convert the FileTime to LocalDateTime
	LocalDateTime ldt =  LocalDateTime.ofInstant( time.toInstant(), ZoneId.systemDefault());

	// Display the number of seconds since epoch for all the Dates
	System.out.println("Date in milliseconds:\t" +  firstDate.getTime() / 1000 );
	System.out.println("FileTime in milliseconds:\t" + time.toMillis() / 1000 );
	System.out.println("LocalDateTime in milliseconds:\t" + ldt.toEpochSecond( ZoneOffset.ofHours( TimeZone.getDefault().getRawOffset() / (3600*1000)  ) ) );
    	System.out.println("LocalDateTime displayed as a String: " 
    		+ ldt.format( DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
    			.withLocale( Locale.ENGLISH ) ) );


The output will be:

Date in milliseconds:	1562366828
FileTime in milliseconds: 1562366828
LocalDateTime milliseconds: 1562370428

LocalDateTime displayed as a String: Jul 5, 2019 3:47:08 PM

All three dates have the same number of seconds since epoch.


Package java.time

Recent Comments