Converting a string to FileTime in java

ε祈祈猫儿з 提交于 2019-12-12 02:19:15

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/17187360/converting-a-string-to-filetime-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!