Самый легкий способ сравнить даты в JavaScript состоит в том, чтобы сначала преобразовать, он на Дату возражает и затем сравнивает эти объекты даты.
Ниже Вас находят объект с тремя функциями:
dates.compare (a, b)
Возвраты число:
dates.inRange (d, запустите, конец)
Возвраты булевская переменная или NaN:
dates.convert
, Используемый другими функциями для преобразования их входа в объект даты. Вход может быть
.
// Source: http://stackoverflow.com/questions/497790
var dates = {
convert:function(d) {
// Converts the date in d to a date-object. The input can be:
// a date object: returned without modification
// an array : Interpreted as [year,month,day]. NOTE: month is 0-11.
// a number : Interpreted as number of milliseconds
// since 1 Jan 1970 (a timestamp)
// a string : Any format supported by the javascript engine, like
// "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
// an object : Interpreted as an object with year, month and date
// attributes. **NOTE** month is 0-11.
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
// Compare two dates (could be of any type supported by the convert
// function above) and returns:
// -1 : if a < b
// 0 : if a = b
// 1 : if a > b
// NaN : if a or b is an illegal date
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
// Checks if date in d is between dates in start and end.
// Returns a boolean or NaN:
// true : if d is between start and end (inclusive)
// false : if d is before start or after end
// NaN : if one or more of the dates is illegal.
// NOTE: The code inside isFinite does an assignment (=).
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
Исходя из вашего вопроса, я предполагаю, что вы видели, что File.createTempFile ()
всегда создает файл, а не просто позволяет вам сгенерировать имя.
Но почему бы просто не вызвать метод, а затем удалить созданный временный файл? createTempFile ()
выполняет всю работу по поиску уникального имени файла в указанном каталоге, и, поскольку вы создали файл, вы можете быть уверены, что его тоже удалите.
File f = File.createTempFile("prefix",null,myDir);
String filename = f.getName();
f.delete();
Использовать метку времени в имени файла?
Конечно, это может не сработать, если у вас очень высокий уровень параллелизма.
Например:
public String getUniqueFileName(String directory, String extension) {
return new File(directory, new StringBuilder().append("prefix")
.append(date.getTime()).append(UUID.randomUUID())
.append(".").append(extension).toString()).getAbsolutePath();
}
Как подсказывает ответ Джона Оксли. UUID может быть решением, так как вы можете использовать 4 разные схемы для их создания. Хотя вероятность столкновения еще небольшая. Если вы объедините отметку времени со случайным UUID, шансы любого столкновения станут исчезающе малыми.
Вы можете попробовать использовать GUID для имени файла.
Вы можете создать файл с любым именем (время, GUID и т. Д.), А затем проверить его, чтобы увидеть, существует ли он уже. Если это так, попробуйте другое имя, чтобы узнать, уникально ли оно.
File f = new File(guid);
if (f.exists()) {
//try another guid
}else{
//you're good to go
}