简体   繁体   中英

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 ie 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM