user2500367
user2500367

Reputation: 19

Converting a string to FileTime in java

I have this problem. PROBLEM: I am making a program in which i am taking input from user via a JFormatedTextField i.e. in string format and then i want this value to be creation time of a file chosen by user.

So I need to uses setTimes() function which only accepts fileTime format. So the PROBLEM is:::: how do I convert the string into an eligible fileTime so that it can be used by the function setTimes() which is predefined in .nio.attribute.

http://www.docjar.com/docs/api/java/nio/file/attribute/FileTime.html

Upvotes: 0

Views: 4760

Answers (2)

Guillaume Polet
Guillaume Polet

Reputation: 47607

Depending on what the format of the input is (I suppose it is something like "dd/MM/yy HH:mm:ss"), you can convert this to a Date using SimpleDateFormat, from the Date you can get the milliseconds using Date.getTime() and finally use that value to build a FileTime with java.nio.file.attribute.FileTime.fromMillis(long)

Something like this should do it:

String text = textField.getText();
Date date = new SimpleDateFormat("dd/MM/yy HH:mm:ss").parse(text);
FileTime time = FileTime.fromMillis(date.getTime());

Upvotes: 3

Manuel Manhart
Manuel Manhart

Reputation: 5475

This would do the trick:

You have to change the date format (new SimpleDateFormat(...) like you give it in the text field and remove the main method indeed.

    public static void main(final String[] args) {
// TODO Auto-generated method stub
String date = "01.01.2013 10:00:10";
long milis;
try {
    milis = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss").parse(date)
        .getTime();
    FileTime fileTime = FileTime.fromMillis(milis);
    System.out
        .println("Time: " + fileTime.toString());
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}

Upvotes: 3

Related Questions