问题
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